ngram
listlengths
0
67.8k
[ "\"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\",", "lira.book import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing", "= { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>>", "width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ),", "TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list = [] for section in", "render def run(self): lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container), key_bindings=get_key_bindings(), mouse_support=True,", "import Layout from prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp from lira.book", "= Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ]", "\", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40,", "= node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render", "sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render = [] for node in", "= { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\":", "Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea from lira.app import", "width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), }", "def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user interface.\"\"\" event.app.exit() return", "text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return", "\"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections = { \"menu\": TextArea( height=40,", "), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render = [] for node", "\"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } }", "style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self):", "chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render))", "\"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", }", "book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container =", "from lira.book import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event):", "KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user", "width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path):", "book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label =", "{ \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \",", "= \"default\" sections_list = [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book =", "\"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\",", "label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]),", "sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents):", "node in contents.children: if node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style]))", "chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit(", "render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"],", "prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label,", "@keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user interface.\"\"\"", "HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea from", "keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit", "from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit,", "\"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles", "Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ),", "multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"),", "\"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles =", "import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window", "height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False,", "contents.children: if node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node))", "style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list = []", "TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False,", "node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira =", "= HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"],", "[] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters =", "\"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\":", "HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ]", "sections[\"status\"], ] ) def get_label(self, contents): render = [] for node in contents.children:", "TextArea from lira.app import LiraApp from lira.book import Book def get_key_bindings(): keys =", "class TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list = [] for section", "= themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\":", "style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\":", "= [] for node in contents.children: if node.is_terminal: text = node.text() style =", "for node in contents.children: if node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text,", "\"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections", "[ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] )", "user interface.\"\"\" event.app.exit() return keys themes = { \"default\": { \"Text\": \"#fff\", \"Strong\":", "if node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\",", "TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]),", "char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list =", "HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render =", "width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]),", "= KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the", "style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class", "= book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container", "__init__(self, path): self.theme = \"default\" sections_list = [] for section in [\"text\", \"prompt\"]:", "self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label,", "contents): render = [] for node in contents.children: if node.is_terminal: text = node.text()", "keys themes = { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff", "self.theme = \"default\" sections_list = [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book", "text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI:", "\"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user interface.\"\"\" event.app.exit() return keys themes", "), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40,", "from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import", "\"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"]", "style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\":", "contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [", "} styles = themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\"", "= node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira", "def __init__(self, path): self.theme = \"default\" sections_list = [] for section in [\"text\",", "prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout", "import LiraApp from lira.book import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\")", "book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render =", "italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\",", "node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\"))", "{ \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\",", "\"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\":", "\"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"],", "themes = { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\",", "node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def", "\"\")) return render def run(self): lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container),", "\"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections = { \"menu\": TextArea(", "sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render", "} } styles = themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"],", "render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira = LiraApp() lira.setup() self.app =", ") def get_label(self, contents): render = [] for node in contents.children: if node.is_terminal:", "\"default\" sections_list = [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path)", "[ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self,", "def run(self): lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container), key_bindings=get_key_bindings(), mouse_support=True, full_screen=True,", "exit the user interface.\"\"\" event.app.exit() return keys themes = { \"default\": { \"Text\":", "sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3,", "path): self.theme = \"default\" sections_list = [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section])", "prompt_toolkit.application import Application from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from", "} class TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list = [] for", "style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme =", "from prompt_toolkit.application import Application from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings", "prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp from lira.book import Book def", "get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will", "\"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\",", "[] for node in contents.children: if node.is_terminal: text = node.text() style = node.tagname", "LiraApp from lira.book import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def", "text=\"Python-Tutorial\\n\" ), \"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10,", "in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents", "] ) def get_label(self, contents): render = [] for node in contents.children: if", "import Label, TextArea from lira.app import LiraApp from lira.book import Book def get_key_bindings():", "\"#00ff00\", } } styles = themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25,", "= chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit(", "will exit the user interface.\"\"\" event.app.exit() return keys themes = { \"default\": {", "def get_label(self, contents): render = [] for node in contents.children: if node.is_terminal: text", "render = [] for node in contents.children: if node.is_terminal: text = node.text() style", "sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render = []", "VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea from lira.app", "return keys themes = { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\":", "render.append(to_formatted_text(text, styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira = LiraApp()", "interface.\"\"\" event.app.exit() return keys themes = { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff", "Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label", "get_label(self, contents): render = [] for node in contents.children: if node.is_terminal: text =", "from lira.app import LiraApp from lira.book import Book def get_key_bindings(): keys = KeyBindings()", "\"status\": TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"],", "return render def run(self): lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container), key_bindings=get_key_bindings(),", "style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"],", "prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp from", "render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira = LiraApp() lira.setup() self.app = Application(", "text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1,", "from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp", "Layout from prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp from lira.book import", "\"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections =", "section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse()", "= self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"],", "VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"], sections[\"status\"], ] ) def", "\"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\":", "prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit,", "from prompt_toolkit.widgets import Label, TextArea from lira.app import LiraApp from lira.book import Book", "), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0,", "run(self): lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container), key_bindings=get_key_bindings(), mouse_support=True, full_screen=True, )", "Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self,", "[\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents =", "chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [", "\"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1,", "the user interface.\"\"\" event.app.exit() return keys themes = { \"default\": { \"Text\": \"#fff\",", "Ctrl-Q or Ctrl-C will exit the user interface.\"\"\" event.app.exit() return keys themes =", "import Application from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers", "\"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\",", "def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C", "or Ctrl-C will exit the user interface.\"\"\" event.app.exit() return keys themes = {", "self.container = HSplit( [ VSplit( [ sections[\"menu\"], sections[\"vseparator\"], HSplit([label, sections[\"prompt\"]]), ] ), sections[\"hseparator\"],", "Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme = \"default\" sections_list", "themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ), \"status\": TextArea(", "for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1]", "TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\": Window(height=0, width=1, char=\"|\",", "@keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user interface.\"\"\" event.app.exit()", "Application from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import", "height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\":", "from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import", "event.app.exit() return keys themes = { \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\",", "\"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0]", "= Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents)", "{ \"default\": { \"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\",", "prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10,", "_(event): \"\"\"Pressing Ctrl-Q or Ctrl-C will exit the user interface.\"\"\" event.app.exit() return keys", "styles = themes[\"default\"] sections = { \"menu\": TextArea( height=40, width=25, style=styles[\"Text\"], text=\"Python-Tutorial\\n\" ),", "sections_list = [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse()", "Ctrl-C will exit the user interface.\"\"\" event.app.exit() return keys themes = { \"default\":", "= [] for section in [\"text\", \"prompt\"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters", "lira.app import LiraApp from lira.book import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\")", "bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\":", "\"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections = {", "Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q or", "\"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme = \"default\"", "\"vseparator\": Window(height=0, width=1, char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def", "\"Text\": \"#fff\", \"Strong\": \"#fff bold\", \"Emphasis\": \"#fff italic\", \"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\":", "] ), sections[\"hseparator\"], sections[\"status\"], ] ) def get_label(self, contents): render = [] for", "in contents.children: if node.is_terminal: text = node.text() style = node.tagname render.append(to_formatted_text(text, styles[style])) else:", "lira = LiraApp() lira.setup() self.app = Application( layout=Layout(self.container), key_bindings=get_key_bindings(), mouse_support=True, full_screen=True, ) self.app.run()", "\"Literal\": \"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\":", "TextArea( height=3, prompt=\">>> \", style=styles[\"Text\"], multiline=False, wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"),", "KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets", "import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from", "import HSplit, VSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.widgets import Label, TextArea", "\"Section\": \"#fff\", \"Separator\": \"#00ff00\", } } styles = themes[\"default\"] sections = { \"menu\":", "sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render", "Label, TextArea from lira.app import LiraApp from lira.book import Book def get_key_bindings(): keys", "import Book def get_key_bindings(): keys = KeyBindings() @keys.add(\"c-c\") @keys.add(\"c-q\") def _(event): \"\"\"Pressing Ctrl-Q", "char=\"|\", style=styles[\"Separator\"]), \"hseparator\": Window(height=1, char=\"-\", style=styles[\"Separator\"]), } class TerminalUI: def __init__(self, path): self.theme", "styles[style])) else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira = LiraApp() lira.setup()", "to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from prompt_toolkit.layout.layout", "merge_formatted_text, to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, VSplit, Window from", "else: render.extend(self.get_label(node)) render.append(to_formatted_text(\"\\n\", \"\")) return render def run(self): lira = LiraApp() lira.setup() self.app", "\"#fff\", \"Paragraph\": \"#fff\", \"CodeBlock\": \"#fff\", \"Prompt\": \"#fff\", \"TestBlock\": \"#fff\", \"Section\": \"#fff\", \"Separator\": \"#00ff00\",", "wrap_lines=False, ), \"text\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"text\"), \"prompt\": TextArea(height=10, width=40, style=styles[\"Text\"], text=\"prompt\"), \"vseparator\":" ]
[ "self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\")", "self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if", "config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x", "self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls =", "None self.flow = None self.ssc = None self.mode = None def load(self, file):", "flow currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step", "= ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow = par.flow simulation =", "# # raise NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\",", "self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class", "= logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\" def __init__(self):", "'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo:", "self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values():", "self.flow = None self.ssc = None self.mode = None def load(self, file): logger.info(\"Loading", "self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source", "ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"]", "config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm =", "0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm", "== \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant", "self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if", "definition in config file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition", "\"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"]", "config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values(): if control['type']", "True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings", "__init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as", "# # if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque", "par.wind_farm turbine = par.turbine flow = par.flow simulation = par.simulation with_adjoint = True", "config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height", "= config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self,", "= self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode", "par.turbine flow = par.flow simulation = par.simulation with_adjoint = True if __name__ ==", "\"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"]", "# self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines:", "open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode =", "-1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par =", "parameters from .yaml file. \"\"\" def __init__(self): self._config = None self.wind_farm = None", "== \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class", "control['type'] == 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break", "self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) #", "step pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant ==", "logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message =", "config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par", "= config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if", "= par.turbine flow = par.flow simulation = par.simulation with_adjoint = True if __name__", "= self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"]", "== \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity", "not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"]", "= config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\",", "= self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"]", "self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator:", "SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step =", "= par.wind_farm turbine = par.turbine flow = par.flow simulation = par.simulation with_adjoint =", "self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def", "implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name", "self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if", "self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as data source implemented\")", "= config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3]", "= \"Missing definition in config file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise", "config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class Turbine: \"\"\" Turbine configuration class", "config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.)", "self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\")", "config file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config", "= config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\":", "= config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.)", "config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not", "self._assign_configuration() except KeyError as ke: message = \"Missing definition in config file, did", "__init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles =", "= self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self,", "self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x)", "if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series =", "# if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque control", "self.wind_farm = None self.turbine = None self.simulation = None self.flow = None self.ssc", "self._config = None self.wind_farm = None self.turbine = None self.simulation = None self.flow", "config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine", "= self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine", "= par.simulation with_adjoint = True if __name__ == '__main__': par = ControlModelParameters() par.load(\"../config/test_config.yaml\")", "= config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"]", "def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine", "\"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size =", "\"\"\" def __init__(self): self._config = None self.wind_farm = None self.turbine = None self.simulation", "= config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation:", "if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque control not", "control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step =", "= self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"])", "self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) #", "self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except", "import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml file.", "logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\"", "config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[])", "self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs", "logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\" def __init__(self): self._config", "= config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles", "self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset", "KeyError(\"Missing definition in config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self,", "2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.)", "config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def", "exc_info=1) raise KeyError(\"Missing definition in config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\")", "Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"]", "turbine = par.turbine flow = par.flow simulation = par.simulation with_adjoint = True if", "logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\" def", "= True if __name__ == '__main__': par = ControlModelParameters() par.load(\"../config/test_config.yaml\") # par.print() #", "self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation =", "= config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine =", "find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file, did not find", "x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius", "try: self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as data source", "in config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream", "self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) #", "self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] #", "self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls =", "__init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length =", "self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow", "= config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes =", "self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length", "= None self.wind_farm = None self.turbine = None self.simulation = None self.flow =", "__init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness", "def __init__(self): self._config = None self.wind_farm = None self.turbine = None self.simulation =", "= None self.flow = None self.ssc = None self.mode = None def load(self,", "except KeyError as ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"]", "self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"])", "= self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\"", "None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls", "self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm =", "for control in self.controls.values(): if control['type'] == 'external': self.with_external_controller = True self.external_controls =", "not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time =", "self.power_reference[:, 1] *= 1e6 # # if self.mode == \"pitch_torque\": # # raise", "None self.ssc = None self.mode = None def load(self, file): logger.info(\"Loading configuration from:", "config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type ==", "= config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in self.yaw_angles]", "config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow = par.flow", "= config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity", "None self.mode = None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try:", "for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else:", "\"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity =", "config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1)", "def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm", "= config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width =", "/ 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial =", "# if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow =", "self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"])", "if control['type'] == 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"]", "not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file, did not", "config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"]", "self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type ==", "NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant", "self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow", "self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class Turbine: \"\"\" Turbine", "Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\":", "1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls", "self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\":", "FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False", "= config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon =", "= config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch", "self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions", "self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque control not implemented.\")", "None self.simulation = None self.flow = None self.ssc = None self.mode = None", "self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height =", "\"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: #", "np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from .yaml", "class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter", "config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\",", "config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently", "= config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type", "yaml import numpy as np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\"", "self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation", "= None self.simulation = None self.flow = None self.ssc = None self.mode =", "did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\")", "file): stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def", "= config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs =", "self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period =", "self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller", "= config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"]", "self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel =", "# raise NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\")", "did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file, did", "config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"]", "def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length", "config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"]", "= config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\",", "config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"]", "load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke:", "\"Missing definition in config file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing", "in self.controls.values(): if control['type'] == 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port", "self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"]", "class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density =", "self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"]", "= self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) #", "config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.)", "= config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values(): if control['type'] == 'external':", "self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective", "= self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation =", "0.) class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic:", "self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights", "configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def", "as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\",", "= config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon =", "= config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights =", "None self.wind_farm = None self.turbine = None self.simulation = None self.flow = None", "self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None", "config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity", "= config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit =", "# else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"])", "config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type =", "class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller =", "= config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type", "def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for", "= self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation", "config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles =", "== 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break #", "= config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"]", "self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"])", "__init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for control", "= config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic", "if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size", "= config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow:", "self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines =", "self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\": #", "file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file,", "config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"]", "settings class Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"]", "config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines", "pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\":", "self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"])", "= config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset =", "config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"]", "as ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window =", "self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in", "Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter =", "Load parameters from .yaml file. \"\"\" def __init__(self): self._config = None self.wind_farm =", "def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2", "config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\") if", "config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"]", "None self.turbine = None self.simulation = None self.flow = None self.ssc = None", "import numpy as np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load", "config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period", "logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file, did not find {}\".format(ke)) logger.info(\"Loaded", "config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density", "self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients", "= True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control", "def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as", "= config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference", "= None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"]", "self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity =", "self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message = \"Missing definition in config", "= config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1)", "self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale", "config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"]", "= self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc", "= config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max =", "= config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective ==", "config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls", "as ke: message = \"Missing definition in config file, did not find {}\".format(ke)", "= config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:,", "True if __name__ == '__main__': par = ControlModelParameters() par.load(\"../config/test_config.yaml\") # par.print() # par.turbine.print()", "= config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif", "self.controls.values(): if control['type'] == 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port =", "self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0,", "{}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file, did not find {}\".format(ke))", "self.controls = config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values(): if control['type'] ==", "in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"]", "self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time", "config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\":", "except KeyError as ke: message = \"Missing definition in config file, did not", "self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit", "= config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller =", "self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width", "config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1]", "config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"])", "SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"]", "in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius =", "\"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm", "numpy as np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters", "if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6", "= config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError", "self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 #", "= np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # # if self.mode == \"pitch_torque\":", "par = ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow = par.flow simulation", "torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step", "self.ssc = None self.mode = None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file))", "self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) #", "config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if", "print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm =", "in config file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in", "class Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError as ke:", "implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period =", "file, did not find {}\".format(ke) logger.error(message, exc_info=1) raise KeyError(\"Missing definition in config file,", "self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine", "with_adjoint = True if __name__ == '__main__': par = ControlModelParameters() par.load(\"../config/test_config.yaml\") # par.print()", "# todo: refine control settings class Turbine: \"\"\" Turbine configuration class \"\"\" def", "self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation", "self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class", "self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in", "= self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator", "= open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode", "self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque =", "config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream =", "KeyError as ke: message = \"Missing definition in config file, did not find", "config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity", "config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"]", "\"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self,", "= config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\")", "self.with_external_controller = False for control in self.controls.values(): if control['type'] == 'external': self.with_external_controller =", "self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\":", "config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values(): if control['type'] == 'external': self.with_external_controller", "self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine =", "== \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow =", "self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation =", "config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"]", "self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine", "self.mode = None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration()", "= config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for control in self.controls.values(): if", "self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius", "= config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"]", "refine control settings class Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction", "self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes", "config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller = False for control in", "= self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port =", "# self.power_reference[:, 1] *= 1e6 # # if self.mode == \"pitch_torque\": # #", "raise NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if", "self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type ==", "self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not", "WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"]", "self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode ==", "\"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC:", "self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation", "config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0)", "self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction", "configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius =", "class SSC: def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls =", "= self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"])", "def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady", "# self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"])", "config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"]", "import yaml import numpy as np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters:", "self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController:", "\"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"])", "self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"]", "self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict): self.kinematic_viscosity = config_dict[\"kinematic_viscosity\"] self.tuning_viscosity =", "elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element =", "self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse", "self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial", "\"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"]", "implemented.\") self.plant = config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class", "config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class Turbine: \"\"\"", "yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode ==", "self.flow = self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys():", "config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"]", "= None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except", "config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective =", "logger.error(\"Only SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step", "= config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] #", "self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon", "# self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # # if self.mode", "class Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter", "np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # # if self.mode == \"pitch_torque\": #", "= yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode", "1) self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data", "self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness =", "simulation = par.simulation with_adjoint = True if __name__ == '__main__': par = ControlModelParameters()", "else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation", "control settings class Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction =", "print(yaml.dump(self._config)) def _assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"])", "*= 1e6 # # if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step", "\"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch torque control not implemented.\") self.plant =", "= config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation =", "= config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class Turbine:", "control in self.controls.values(): if control['type'] == 'external': self.with_external_controller = True self.external_controls = config_dict[\"external_controller\"][\"controls\"]", "self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon", "configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message = \"Missing", "self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # # if self.mode ==", "message = \"Missing definition in config file, did not find {}\".format(ke) logger.error(message, exc_info=1)", "= None self.ssc = None self.mode = None def load(self, file): logger.info(\"Loading configuration", "self.turbine = None self.simulation = None self.flow = None self.ssc = None self.mode", "= config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self, config_dict):", "config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic =", "= None self.mode = None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file)", "file. \"\"\" def __init__(self): self._config = None self.wind_farm = None self.turbine = None", "config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch =", "not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"]", "find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config =", "wind_farm = par.wind_farm turbine = par.turbine flow = par.flow simulation = par.simulation with_adjoint", "raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step =", "if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class", "= config_dict[\"data\"] par = ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow =", "__init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise NotImplementedError(\"Steady flow", "self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if", "config_dict): try: self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA as data", "NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"]", "= config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters() wind_farm", "class ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\" def __init__(self): self._config =", "= config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse =", "== \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # #", "if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"])", "def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles", "self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow", "Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: # raise", "_assign_configuration(self): self.mode = self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine =", "config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self,", "if self.ssc.type == \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"])", "else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class", "ke: message = \"Missing definition in config file, did not find {}\".format(ke) logger.error(message,", "== \"gradient_step\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) # else:", "from .yaml file. \"\"\" def __init__(self): self._config = None self.wind_farm = None self.turbine", "self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"])", "def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self):", "= config_dict.get(\"plant\", \"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def", "not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config", "self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells", "Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only", "False for control in self.controls.values(): if control['type'] == 'external': self.with_external_controller = True self.external_controls", "file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message", "par.flow simulation = par.simulation with_adjoint = True if __name__ == '__main__': par =", "= config_dict[\"kinematic_viscosity\"] self.tuning_viscosity = config_dict[\"tuning_viscosity\"] self.density = config_dict[\"density\"] self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length =", "self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period = config_dict.get(\"transient_period\",", "as np import logging logger = logging.getLogger(\"cm.conf\") class ControlModelParameters: \"\"\" Load parameters from", "todo: refine control settings class Turbine: \"\"\" Turbine configuration class \"\"\" def __init__(self,config_dict):", "\"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *= 1e6 # # if", "# if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic:", "self._config[\"mode\"] if self.mode == \"simulation\": self.wind_farm = self.WindFarm(self._config[\"wind_farm\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) self.simulation =", "self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type", "if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try:", "np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if", "self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells =", "self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"]", "self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict):", "self.Flow(self._config[\"flow\"]) # else: # self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator =", "config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"]", "# raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step", "self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def", "config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError as", "== \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict): try: self.source =", "None def load(self, file): logger.info(\"Loading configuration from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError", "config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series = np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element", "= config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type =", "ControlModelParameters: \"\"\" Load parameters from .yaml file. \"\"\" def __init__(self): self._config = None", "stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config)) def _assign_configuration(self):", "__init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements =", "= config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction =", "try: self._assign_configuration() except KeyError as ke: message = \"Missing definition in config file,", "= config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients =", "class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"] # if not self.is_dynamic: #", "0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def __init__(self, config_dict): self.is_dynamic = config_dict[\"is_dynamic\"]", "source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1) self.transient_period", "= config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"]", "_load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader) def print(self): print(yaml.dump(self._config))", "self.transient_period = config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data =", "np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict):", "flow = par.flow simulation = par.simulation with_adjoint = True if __name__ == '__main__':", "KeyError as ke: logger.error(\"Only SOWFA as data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window", "class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions =", "self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"] self.with_external_controller", "{}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config = yaml.load(stream=stream,", "self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self, config_dict): self.port", "config_dict[\"diameter\"] self.radius = self.diameter / 2 self.thickness = config_dict[\"thickness\"] self.hub_height = config_dict[\"hub_height\"] self.kernel", "if not self.is_dynamic: # raise NotImplementedError(\"Steady flow currently not implemented\") if self.is_dynamic: self.total_time", "definition in config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file):", "self.Turbine(self._config[\"turbine\"]) self.simulation = self.Simulation(self._config[\"simulation\"]) self.flow = self.Flow(self._config[\"flow\"]) if self.mode == \"supercontroller\": self.ssc =", ".yaml file. \"\"\" def __init__(self): self._config = None self.wind_farm = None self.turbine =", "\"cm\") if self.plant == \"sowfa\": self.sowfa_time_step = config_dict[\"sowfa_time_step\"] class Estimator: def __init__(self, config_dict):", "== \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type == \"gradient_step\":", "def __init__(self, config_dict): try: self.source = config_dict[\"source\"] except KeyError as ke: logger.error(\"Only SOWFA", "self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions", "[np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius = config_dict[\"refine_radius\"]", "self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm: def __init__(self, config_dict):", "config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type", "config_dict): self.size = config_dict[\"size\"] self.cells = config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"])", "= np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"]", "1e6 # # if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient step pitch", "= [np.array(x) for x in self.yaw_angles] self.do_refine_turbines = config_dict[\"do_refine_turbines\"] if self.do_refine_turbines: self.refine_radius =", "= config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class Turbine: \"\"\" Turbine configuration", "raise KeyError(\"Missing definition in config file, did not find {}\".format(ke)) logger.info(\"Loaded configuration.\") def", "self.mixing_length = config_dict[\"mixing_length\"] self.wake_mixing_length = config_dict[\"wake_mixing_length\"] self.wake_mixing_width = config_dict[\"wake_mixing_width\"] self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max", "config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1)", "break # todo: refine control settings class Turbine: \"\"\" Turbine configuration class \"\"\"", "if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name =", "ControlModelParameters() wind_farm = par.wind_farm turbine = par.turbine flow = par.flow simulation = par.simulation", "self.save_logs = config_dict[\"save_logs\"] self.dimensions = config_dict[\"dimensions\"] self.probes = config_dict.get(\"probes\",[]) class Flow: def __init__(self,", "\"\"\" Load parameters from .yaml file. \"\"\" def __init__(self): self._config = None self.wind_farm", "config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity = config_dict[\"inflow_velocity\"] elif self.type == \"series\": self.inflow_velocity_series", "config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements = config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"]", "config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict):", "1] *= 1e6 # # if self.mode == \"pitch_torque\": # # raise NotImplementedError(\"gradient", "if self.mode == \"supercontroller\": self.ssc = self.SSC(self._config[\"ssc\"]) self.turbine = self.Turbine(self._config[\"turbine\"]) # if self.ssc.type", "par.simulation with_adjoint = True if __name__ == '__main__': par = ControlModelParameters() par.load(\"../config/test_config.yaml\") #", "self.power_scale = config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\",", "self.simulation = None self.flow = None self.ssc = None self.mode = None def", "self.refine_radius = config_dict[\"refine_radius\"] else: self.refine_radius = None self.controller = self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def", "config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if self.type == \"steady\": self.inflow_velocity =", "config_dict.get(\"power_scale\",1.) self.yaw_rate_limit = config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque", "# if self.objective == \"tracking\": # self.power_reference = np.array(config_dict[\"power_reference\"]) # self.power_reference[:, 1] *=", "config_dict.get(\"transient_time\",-1) # self.objective = config_dict[\"objective\"] # if self.objective == \"tracking\": # self.power_reference =", "self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"]", "self.wake_mixing_offset = config_dict[\"wake_mixing_offset\"] self.wake_mixing_ml_max = config_dict[\"wake_mixing_ml_max\"] self.continuity_correction = config_dict[\"continuity_correction\"] self.type = config_dict[\"type\"] if", "currently not implemented\") if self.is_dynamic: self.total_time = config_dict[\"total_time\"] self.time_step = config_dict[\"time_step\"] self.write_time_step =", "= config_dict.get(\"transient_period\", -1) self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"]", "= self.FarmController(config_dict[\"farm_controller\"]) class FarmController: def __init__(self, config_dict): self.control_discretisation = config_dict[\"control_discretisation\"] self.controls = config_dict[\"controls\"]", "data source implemented\") self.estimation_type = config_dict[\"type\"] self.assimilation_window = config_dict[\"assimilation_window\"] self.forward_step = config_dict.get(\"forward_step\", 1)", "= config_dict[\"hub_height\"] self.kernel = config_dict[\"kernel\"] self.force_scale_axial = config_dict.get(\"force_scale_axial\",1.) self.force_scale_transverse = config_dict.get(\"force_scale_transverse\",1.) self.power_scale =", "= config_dict[\"cells\"] self.positions = config_dict[\"positions\"] self.yaw_angles = np.deg2rad(config_dict[\"yaw_angles\"]) # self.yaw_angles = [np.array(x) for", "config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.) class Simulation: def", "config_dict.get(\"yaw_rate_limit\",-1) self.coefficients = config_dict.get(\"coefficients\", \"induction\") self.pitch = config_dict.get(\"pitch\", 0.) self.torque = config_dict.get(\"torque\", 0.)", "__init__(self): self._config = None self.wind_farm = None self.turbine = None self.simulation = None", "= par.flow simulation = par.simulation with_adjoint = True if __name__ == '__main__': par", "self.external_controls = config_dict[\"external_controller\"][\"controls\"] self.port = config_dict[\"external_controller\"][\"port\"] break # todo: refine control settings class", "# self.simulation = self.Simulation(self._config[\"simulation\"]) if \"estimator\" in self._config.keys(): self.estimator = self.Estimator(self._config[\"estimator\"]) class WindFarm:", "Turbine configuration class \"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius", "= None self.turbine = None self.simulation = None self.flow = None self.ssc =", "\"\"\" def __init__(self,config_dict): self.axial_induction = config_dict[\"axial_induction\"] self.diameter = config_dict[\"diameter\"] self.radius = self.diameter /", "= False for control in self.controls.values(): if control['type'] == 'external': self.with_external_controller = True", "{}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message = \"Missing definition in", "= config_dict[\"external_measurements\"] self.control_discretisation = config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time =", "= config_dict[\"time_step\"] self.write_time_step = config_dict[\"write_time_step\"] self.name = config_dict[\"name\"] self.save_logs = config_dict[\"save_logs\"] self.dimensions =", "self.prediction_period = config_dict.get(\"prediction_period\", 0) self.cost_function_weights = config_dict[\"cost_function_weights\"] self.data = config_dict[\"data\"] par = ControlModelParameters()", "= np.array(config_dict[\"inflow_velocity_series\"]) self.inflow_velocity = self.inflow_velocity_series[0, 1:3] self.finite_element = config_dict.get(\"finite_element\",\"TH\") class SSC: def __init__(self,", "def __init__(self, config_dict): self.port = config_dict[\"port\"] self.controls = config_dict[\"controls\"] self.external_controls = config_dict[\"external_controls\"] self.external_measurements", "= config_dict[\"control_discretisation\"] self.prediction_horizon = config_dict[\"prediction_horizon\"] self.control_horizon = config_dict[\"control_horizon\"] self.transient_time = config_dict.get(\"transient_time\",-1) # self.objective", "from: {}\".format(file)) self._load_configuration_from_yaml(file) try: self._assign_configuration() except KeyError as ke: message = \"Missing definition", "logger.info(\"Loaded configuration.\") def _load_configuration_from_yaml(self, file): stream = open(file, \"r\") self._config = yaml.load(stream=stream, Loader=yaml.SafeLoader)" ]
[ "delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab,", "TO AN INDEX words_number += 1 graph = np.zeros((words_number, words_number)) # words_number X", "window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns:", "sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank):", "[] for word in sentence: if word in keywords_set: one.append(word) else: if len(one)", "= 0 for word_list in _vertex_source: for word in word_list: if word not", "networkx as nx import numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from", "keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num:", "{} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result =", "介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args:", "in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__':", "keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num or phrase", "index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0", "_edge_source = edge_source words_number = 0 for word_list in _vertex_source: for word in", "# Author: <NAME> # Mail: <EMAIL> # Created Time: 2021-09-04 # Description: #", "not in word_index: word_index[word] = words_number index_word[words_number] = word # MAP WORD TO", "page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns:", "1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this", "Returns: \"\"\" if window < 2: window = 2 for x in range(1,", "< 2: window = 2 for x in range(1, window): if x >=", "self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None):", "len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if self.text.count(phrase) >=", "2 for x in range(1, window): if x >= len(word_list): break word_list2 =", "is a dict DIRECTLY GET THE SCORE FOR ALL THIS MATRIX sorted_scores =", "关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result", "sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window = 5 num =", "MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score in sorted_scores:", "in _vertex_source: for word in word_list: if word not in word_index: word_index[word] =", "item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__': text =", "word_list2) for r in res: yield r for word_list in _edge_source: for w1,", "import networkx as nx import numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags", "关键短语的列表。 \"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set()", "word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] =", "window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source,", "# concat在一起 if len(one) == 0: continue else: one = [] # 兜底", "= [] count = 0 for item in keywords: if count >= num:", "import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref", "self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count = 0 for item in", "page_rank_config=page_rank_config) result = [] count = 0 for item in keywords: if count", "w2 in combine(word_list, window): if w1 in word_index and w2 in word_index: index1", "in word_index: word_index[word] = words_number index_word[words_number] = word # MAP WORD TO AN", "TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len,", "window: int, 窗口大小。 Returns: \"\"\" if window < 2: window = 2 for", "in self.words_no_filter: one = [] for word in sentence: if word in keywords_set:", "\"\"\" page_rank_config = {'alpha': 0.85, } if not page_rank_config else page_rank_config sorted_words =", "sorted_words = [] word_index = {} index_word = {} _vertex_source = vertex_source _edge_source", "word in keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if", "# -----------------------------------------------------------------------# import networkx as nx import numpy as np from knlp.common.constant import", "5 num = 20 word_min_len = 2 need_key_phrase = True tr4w = TextRank4Keyword()", "window): if w1 in word_index and w2 in word_index: index1 = word_index[w1] index2", "if not page_rank_config else page_rank_config sorted_words = [] word_index = {} index_word =", "# !/usr/bin/python # -*- coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: textrank_keyword #", "window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase:", "num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords =", "self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count = 0 for item in keywords:", "-*- # -----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL>", "for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for", "Mail: <EMAIL> # Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as", "sentence: if word in keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) #", "1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num", "word_min_len: result.append(item) count += 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。", "reverse=True) for index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words", "\"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags,", "allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\"", "graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config)", "def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window:", "item[1], reverse=True) for index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return", "delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha':", "2: window = 2 for x in range(1, window): if x >= len(word_list):", "获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\"", "} if not page_rank_config else page_rank_config sorted_words = [] word_index = {} index_word", "DIRECTLY GET THE SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item:", "in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点", "self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source:", "_vertex_source: for word in word_list: if word not in word_index: word_index[word] = words_number", "window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if not", "TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求", "list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window < 2:", "self.words_no_filter: one = [] for word in sentence: if word in keywords_set: one.append(word)", "AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window", "@staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边", "[phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num or phrase in self.label_set]", "兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if", "word_index = {} index_word = {} _vertex_source = vertex_source _edge_source = edge_source words_number", "一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if not page_rank_config", "!/usr/bin/python # -*- coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: textrank_keyword # Author:", "构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if", "nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY", "in keywords: if count >= num: break if len(item.word) >= word_min_len: result.append(item) count", "word_index and w2 in word_index: index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置", "= nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY GET THE SCORE FOR", "<NAME> # Mail: <EMAIL> # Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import", "nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY GET THE SCORE FOR ALL", "{} _vertex_source = vertex_source _edge_source = edge_source words_number = 0 for word_list in", "\"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags:", "获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count =", "for sentence in self.words_no_filter: one = [] for word in sentence: if word", "count = 0 for item in keywords: if count >= num: break if", "min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)])", "return [phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num or phrase in", "= TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num,", "= 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores =", "word_min_len = 2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output =", "File Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL> # Created Time: 2021-09-04", "one = [] for word in sentence: if word in keywords_set: one.append(word) else:", "[] count = 0 for item in keywords: if count >= num: break", "allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file,", "np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import", "text = \"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len = 2 need_key_phrase", "Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config)", "X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str,", "**page_rank_config) # this is a dict DIRECTLY GET THE SCORE FOR ALL THIS", "words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。", "get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/", "index_word = {} _vertex_source = vertex_source _edge_source = edge_source words_number = 0 for", "min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序", "a dict DIRECTLY GET THE SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(),", "else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue", "index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0", "= tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight,", "word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window <", "from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见", "zip(word_list, word_list2) for r in res: yield r for word_list in _edge_source: for", "\"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for", "in combine(word_list, window): if w1 in word_index and w2 in word_index: index1 =", "# -----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL> #", "def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window: int,", "scores = nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY GET THE SCORE", "get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数", "res: yield r for word_list in _edge_source: for w1, w2 in combine(word_list, window):", "\"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(),", "1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num or", "not page_rank_config else page_rank_config sorted_words = [] word_index = {} index_word = {}", "np.zeros((words_number, words_number)) # words_number X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args:", "0 for item in keywords: if count >= num: break if len(item.word) >=", "MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window:", "result.append(item) count += 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取", "output = {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item", "sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score in sorted_scores: item", "if len(one) == 0: continue else: one = [] # 兜底 if len(one)", "[] word_index = {} index_word = {} _vertex_source = vertex_source _edge_source = edge_source", "rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count = 0", "二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if", "# Mail: <EMAIL> # Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx", "graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is", "phrase in keyphrases if self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod def", "allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2,", "window = 5 num = 20 word_min_len = 2 need_key_phrase = True tr4w", "1 graph = np.zeros((words_number, words_number)) # words_number X words_number MATRIX def combine(word_list, window=2):", "r for word_list in _edge_source: for w1, w2 in combine(word_list, window): if w1", "tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count])", "for index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if", "import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class", "停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self,", "Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item", "+= 1 graph = np.zeros((words_number, words_number)) # words_number X words_number MATRIX def combine(word_list,", "word_list2 = word_list[x:] res = zip(word_list, word_list2) for r in res: yield r", "= {} index_word = {} _vertex_source = vertex_source _edge_source = edge_source words_number =", "_edge_source: for w1, w2 in combine(word_list, window): if w1 in word_index and w2", ">= min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\"", "使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word", "page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if not page_rank_config else", "page_rank_config = {'alpha': 0.85, } if not page_rank_config else page_rank_config sorted_words = []", "SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for", "= zip(word_list, word_list2) for r in res: yield r for word_list in _edge_source:", "def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num:", "= tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase in tr4w.get_keyphrases(keywords_num=10, min_occur_num=2): output['key_phrase'].append(phrase)", "in word_index and w2 in word_index: index1 = word_index[w1] index2 = word_index[w2] #", "最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases", "Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords", "默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85,", "coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME> # Mail:", "'__main__': text = \"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len = 2", "= word # MAP WORD TO AN INDEX words_number += 1 graph =", "allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args:", "word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter: one = [] for word", "# this is a dict DIRECTLY GET THE SCORE FOR ALL THIS MATRIX", "x in range(1, window): if x >= len(word_list): break word_list2 = word_list[x:] res", "x >= len(word_list): break word_list2 = word_list[x:] res = zip(word_list, word_list2) for r", "edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, }", "of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window < 2: window", "min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数", "set() for sentence in self.words_no_filter: one = [] for word in sentence: if", "num = 20 word_min_len = 2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text,", "for w1, w2 in combine(word_list, window): if w1 in word_index and w2 in", "= {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in", "Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config =", "word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph =", "if count >= num: break if len(item.word) >= word_min_len: result.append(item) count += 1", "# Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as nx import", "\"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = []", "> 1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num", "nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY GET THE", "= [] for word in sentence: if word in keywords_set: one.append(word) else: if", "vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha':", "textrank_keyword # Author: <NAME> # Mail: <EMAIL> # Created Time: 2021-09-04 # Description:", "w1 in word_index and w2 in word_index: index1 = word_index[w1] index2 = word_index[w2]", "knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。", "word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict", "if len(item.word) >= word_min_len: result.append(item) count += 1 return result def get_keyphrases(self, keywords_num=12,", "knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18", "\"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns:", "if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue else:", "in _edge_source: for w1, w2 in combine(word_list, window): if w1 in word_index and", "INDEX words_number += 1 graph = np.zeros((words_number, words_number)) # words_number X words_number MATRIX", "窗口大小。 Returns: \"\"\" if window < 2: window = 2 for x in", "dict DIRECTLY GET THE SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda", "num: break if len(item.word) >= word_min_len: result.append(item) count += 1 return result def", "phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source:", "{} index_word = {} _vertex_source = vertex_source _edge_source = edge_source words_number = 0", "\"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len = 2 need_key_phrase = True", "= set() for sentence in self.words_no_filter: one = [] for word in sentence:", "int, 窗口大小。 Returns: \"\"\" if window < 2: window = 2 for x", "from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file,", "ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径", "= set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in", "result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args:", "words_number += 1 graph = np.zeros((words_number, words_number)) # words_number X words_number MATRIX def", "keywords: if count >= num: break if len(item.word) >= word_min_len: result.append(item) count +=", "delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num:", "keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count = 0 for", "= vertex_source _edge_source = edge_source words_number = 0 for word_list in _vertex_source: for", "Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases =", "len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue else: one", "https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file:", "= 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) #", "0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\"", "for r in res: yield r for word_list in _edge_source: for w1, w2", "# 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph)", "\"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }):", "获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。", "2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [],", "-----------------------------------------------------------------------# import networkx as nx import numpy as np from knlp.common.constant import sentence_delimiters,", "GET THE SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1],", "keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set", "if word in keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起", "str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window < 2: window =", "_vertex_source = vertex_source _edge_source = edge_source words_number = 0 for word_list in _vertex_source:", "= sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score in sorted_scores: item =", "edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config:", "graph = np.zeros((words_number, words_number)) # words_number X words_number MATRIX def combine(word_list, window=2): \"\"\"", "word_list: if word not in word_index: word_index[word] = words_number index_word[words_number] = word #", "{\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords:", "= edge_source words_number = 0 for word_list in _vertex_source: for word in word_list:", "words_number X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of", "__init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters:", "\"\"\" if window < 2: window = 2 for x in range(1, window):", "word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source,", "有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores", "# MAP WORD TO AN INDEX words_number += 1 graph = np.zeros((words_number, words_number))", "0.85, } if not page_rank_config else page_rank_config sorted_words = [] word_index = {}", "= {} _vertex_source = vertex_source _edge_source = edge_source words_number = 0 for word_list", "len(one) == 0: continue else: one = [] # 兜底 if len(one) >", "yield r for word_list in _edge_source: for w1, w2 in combine(word_list, window): if", "else page_rank_config sorted_words = [] word_index = {} index_word = {} _vertex_source =", "key=lambda item: item[1], reverse=True) for index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score)", "in range(1, window): if x >= len(word_list): break word_list2 = word_list[x:] res =", "for x in range(1, window): if x >= len(word_list): break word_list2 = word_list[x:]", "from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text", "set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter:", "page_rank_config sorted_words = [] word_index = {} index_word = {} _vertex_source = vertex_source", "if word not in word_index: word_index[word] = words_number index_word[words_number] = word # MAP", "for word_list in _edge_source: for w1, w2 in combine(word_list, window): if w1 in", "= word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph", "res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word,", "for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter: one", "and w2 in word_index: index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置 =", "continue else: one = [] # 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return", "基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)):", "THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score in", "暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\"", "word_index[word] = words_number index_word[words_number] = word # MAP WORD TO AN INDEX words_number", "= 2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\":", "个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set =", "keyphrases if self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source,", "num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config:", "= words_number index_word[words_number] = word # MAP WORD TO AN INDEX words_number +=", "AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\"", "window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns:", "combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。", "word in sentence: if word in keywords_set: one.append(word) else: if len(one) > 1:", "WORD TO AN INDEX words_number += 1 graph = np.zeros((words_number, words_number)) # words_number", "-*- coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME> #", "> 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue else: one =", "__name__ == '__main__': text = \"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len", "1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is a dict", "need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\":", "# 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases", "\"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text", "tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords =", "= self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count = 0 for item", "0: continue else: one = [] # 兜底 if len(one) > 1: keyphrases.add(''.join(one))", "keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence", "concat在一起 if len(one) == 0: continue else: one = [] # 兜底 if", "if x >= len(word_list): break word_list2 = word_list[x:] res = zip(word_list, word_list2) for", "= 20 word_min_len = 2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True)", "2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as nx import numpy as np", "item in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter: one =", "AN INDEX words_number += 1 graph = np.zeros((words_number, words_number)) # words_number X words_number", "word_min_len=word_min_len, window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if", "= 0 for item in keywords: if count >= num: break if len(item.word)", "words_number index_word[words_number] = word # MAP WORD TO AN INDEX words_number += 1", "Author: <NAME> # Mail: <EMAIL> # Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------#", "= {'alpha': 0.85, } if not page_rank_config else page_rank_config sorted_words = [] word_index", "tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase in tr4w.get_keyphrases(keywords_num=10, min_occur_num=2): output['key_phrase'].append(phrase) print(output)", "page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {}", "nx import numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import", "sentence in self.words_no_filter: one = [] for word in sentence: if word in", "rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags,", "= word_list[x:] res = zip(word_list, word_list2) for r in res: yield r for", "w2 in word_index: index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0", "{'alpha': 0.85, } if not page_rank_config else page_rank_config sorted_words = [] word_index =", "pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if not page_rank_config else page_rank_config", "edge_source words_number = 0 for word_list in _vertex_source: for word in word_list: if", "+= 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。", "for item in keywords: if count >= num: break if len(item.word) >= word_min_len:", "in word_list: if word not in word_index: word_index[word] = words_number index_word[words_number] = word", "keyphrases = set() for sentence in self.words_no_filter: one = [] for word in", "[] # 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase in", "MAP WORD TO AN INDEX words_number += 1 graph = np.zeros((words_number, words_number)) #", "# Description: # -----------------------------------------------------------------------# import networkx as nx import numpy as np from", "= 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is a", "sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__': text", "one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0:", "TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self,", "}): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" #", ">= num: break if len(item.word) >= word_min_len: result.append(item) count += 1 return result", "range(1, window): if x >= len(word_list): break word_list2 = word_list[x:] res = zip(word_list,", "or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args:", "return sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window = 5 num", "break word_list2 = word_list[x:] res = zip(word_list, word_list2) for r in res: yield", "if self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source, edge_source, window=2,", "import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性", "tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window)", "<EMAIL> # Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as nx", "THE SCORE FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)", "kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase in tr4w.get_keyphrases(keywords_num=10, min_occur_num=2):", "20 word_min_len = 2 need_key_phrase = True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output", "\"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\"", "in res: yield r for word_list in _edge_source: for w1, w2 in combine(word_list,", "word in word_list: if word not in word_index: word_index[word] = words_number index_word[words_number] =", "word_list in _edge_source: for w1, w2 in combine(word_list, window): if w1 in word_index", "stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。", "for word_list in _vertex_source: for word in word_list: if word not in word_index:", "Description: # -----------------------------------------------------------------------# import networkx as nx import numpy as np from knlp.common.constant", "二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config = {'alpha': 0.85,", "word_list[x:] res = zip(word_list, word_list2) for r in res: yield r for word_list", "res = zip(word_list, word_list2) for r in res: yield r for word_list in", "word_index: index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] =", "count >= num: break if len(item.word) >= word_min_len: result.append(item) count += 1 return", "private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\"", "个关键词来构造短语 Args: keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for", "as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util", "if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase in keyphrases if self.text.count(phrase)", "window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置", "class TextRank4Keyword(TextRank): \"\"\" 这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def", "score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ ==", "True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords", "Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters)", "keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue else: one = [] #", "words_number)) # words_number X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list:", "\"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count =", "vertex_source _edge_source = edge_source words_number = 0 for word_list in _vertex_source: for word", "in word_index: index1 = word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2]", "item in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase", "len(word_list): break word_list2 = word_list[x:] res = zip(word_list, word_list2) for r in res:", "# 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window, page_rank_config=page_rank_config) result = [] count", "= AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\"", "else: one = [] # 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase", "in keyphrases if self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod def sort_words(vertex_source,", ">= word_min_len: result.append(item) count += 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\"", "index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item) return sorted_words if __name__", "[], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count", "# words_number X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list", "keywords_num: 关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item in", "Returns: \"\"\" page_rank_config = {'alpha': 0.85, } if not page_rank_config else page_rank_config sorted_words", "def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性", "def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window:", "window = 2 for x in range(1, window): if x >= len(word_list): break", "这个函数实现了利用Text rank算法来实现关键词提取的功能。 基础的思路就是先分词,然后计算每个词语的权重,最后按照顺序排列,得到重要性 暂时不考虑英文的需求 介绍请见 https://www.jiqizhixin.com/articles/2018-12-28-18 ref https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None,", "count += 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num", "https://github.com/letiantian/TextRank4ZH/blob/master/textrank4zh/ \"\"\" def __init__(self, stop_words_file=get_default_stop_words_file(), private_vocab=None, allow_speech_tags=allow_speech_tags, delimiters=\"|\".join(sentence_delimiters)): \"\"\" Args: stop_words_file: 停用词的文件路径 label_set:", "关键词的个数 min_occur_num: 最少出现次数 Returns: 关键短语的列表。 \"\"\" keywords_set = set([item.word for item in self.get_keywords(num=keywords_num,", "words_number = 0 for word_list in _vertex_source: for word in word_list: if word", "combine(word_list, window): if w1 in word_index and w2 in word_index: index1 = word_index[w1]", "index_word[words_number] = word # MAP WORD TO AN INDEX words_number += 1 graph", "Args: word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window", "result = [] count = 0 for item in keywords: if count >=", "keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one) ==", "word not in word_index: word_index[word] = words_number index_word[words_number] = word # MAP WORD", "ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score", "len(item.word) >= word_min_len: result.append(item) count += 1 return result def get_keyphrases(self, keywords_num=12, min_occur_num=2):", "# -*- coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME>", "= nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph, **page_rank_config) # this is a dict DIRECTLY GET", "FOR ALL THIS MATRIX sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for index,", "window): if x >= len(word_list): break word_list2 = word_list[x:] res = zip(word_list, word_list2)", "sorted(scores.items(), key=lambda item: item[1], reverse=True) for index, score in sorted_scores: item = AttrDict(word=index_word[index],", "get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len:", "import numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank", "== 0: continue else: one = [] # 兜底 if len(one) > 1:", "for phrase in keyphrases if self.text.count(phrase) >= min_occur_num or phrase in self.label_set] @staticmethod", "this is a dict DIRECTLY GET THE SCORE FOR ALL THIS MATRIX sorted_scores", "page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序 keywords = self.sort_words(self._vertex_source, self._edge_source, window=window,", "= 5 num = 20 word_min_len = 2 need_key_phrase = True tr4w =", "lower=True) output = {\"key_words\": [], \"key_phrase\": []} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for", "item in keywords: if count >= num: break if len(item.word) >= word_min_len: result.append(item)", "= 2 for x in range(1, window): if x >= len(word_list): break word_list2", "Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL> # Created Time: 2021-09-04 #", "1。0 graph[index1][index2] = 1.0 graph[index2][index1] = 1.0 nx_graph = nx.from_numpy_matrix(graph) scores = nx.pagerank(nx_graph,", "if w1 in word_index and w2 in word_index: index1 = word_index[w1] index2 =", "break if len(item.word) >= word_min_len: result.append(item) count += 1 return result def get_keyphrases(self,", "one = [] # 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for", "-----------------------------------------------------------------------# # File Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL> # Created", "0 for word_list in _vertex_source: for word in word_list: if word not in", "word_index: word_index[word] = words_number index_word[words_number] = word # MAP WORD TO AN INDEX", "if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window = 5 num = 20", "self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter: one = [] for", "= [] # 兜底 if len(one) > 1: keyphrases.add(''.join(one)) return [phrase for phrase", "= \"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len = 2 need_key_phrase =", "weight=score) sorted_words.append(item) return sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window =", "return result def get_keyphrases(self, keywords_num=12, min_occur_num=2): \"\"\" 获取关键短语。 获取 keywords_num 个关键词构造的可能出现的短语,要求这个短语在原文本中至少出现的次数为min_occur_num。 使用有限的keywords_num 个关键词来构造短语", "res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase in tr4w.get_keyphrases(keywords_num=10,", ">= len(word_list): break word_list2 = word_list[x:] res = zip(word_list, word_list2) for r in", "Created Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as nx import numpy", "stop_words_file: 停用词的文件路径 label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def", "w1, w2 in combine(word_list, window): if w1 in word_index and w2 in word_index:", "knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from knlp.utils.util import get_default_stop_words_file, AttrDict", "page_rank_config else page_rank_config sorted_words = [] word_index = {} index_word = {} _vertex_source", "= [] word_index = {} index_word = {} _vertex_source = vertex_source _edge_source =", "word # MAP WORD TO AN INDEX words_number += 1 graph = np.zeros((words_number,", "= word_index[w1] index2 = word_index[w2] # 有链接的位置 = 1。0 graph[index1][index2] = 1.0 graph[index2][index1]", "= np.zeros((words_number, words_number)) # words_number X words_number MATRIX def combine(word_list, window=2): \"\"\" 构造在window下的单词组合,用来构造单词之间的边。", "== '__main__': text = \"测试分词的结果是否符合预期\" window = 5 num = 20 word_min_len =", "if window < 2: window = 2 for x in range(1, window): if", "in self.get_keywords(num=keywords_num, word_min_len=1)]) keyphrases = set() for sentence in self.words_no_filter: one = []", "Time: 2021-09-04 # Description: # -----------------------------------------------------------------------# import networkx as nx import numpy as", "\"\"\" 构造在window下的单词组合,用来构造单词之间的边。 Args: word_list: list of str, 由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\"", "private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\" 获取最重要的num个长度大于等于word_min_len的关键词。", "要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1,", "window < 2: window = 2 for x in range(1, window): if x", "= True tr4w = TextRank4Keyword() tr4w.analyze(text=text, lower=True) output = {\"key_words\": [], \"key_phrase\": []}", "in sentence: if word in keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one))", "for word in word_list: if word not in word_index: word_index[word] = words_number index_word[words_number]", "由单词组成的列表。 window: int, 窗口大小。 Returns: \"\"\" if window < 2: window = 2", "sorted_words.append(item) return sorted_words if __name__ == '__main__': text = \"测试分词的结果是否符合预期\" window = 5", "1: keyphrases.add(''.join(one)) # concat在一起 if len(one) == 0: continue else: one = []", "item: item[1], reverse=True) for index, score in sorted_scores: item = AttrDict(word=index_word[index], weight=score) sorted_words.append(item)", "将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边 page_rank_config: pagerank的设置 Returns: \"\"\" page_rank_config", "word_list in _vertex_source: for word in word_list: if word not in word_index: word_index[word]", "in res_keywords: kw_count = tr4w.text.count(item.word) output[\"key_words\"].append([item.word, item.weight, kw_count]) if need_key_phrase: for phrase in", "numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank import TextRank from", "for word in sentence: if word in keywords_set: one.append(word) else: if len(one) >", "window=window, page_rank_config=page_rank_config) result = [] count = 0 for item in keywords: if", "[]} res_keywords = tr4w.get_keywords(num=num, word_min_len=word_min_len, window=window) for item in res_keywords: kw_count = tr4w.text.count(item.word)", "in keywords_set: one.append(word) else: if len(one) > 1: keyphrases.add(''.join(one)) # concat在一起 if len(one)", "super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6, window=2, word_min_len=1, page_rank_config={'alpha': 0.85, }): \"\"\"", "label_set: allow_speech_tags: 要保留的词性 delimiters: 默认值是`?!;?!。;…\\n`,用来将文本拆分为句子。 \"\"\" super().__init__(stop_words_file=stop_words_file, private_vocab=private_vocab, allow_speech_tags=allow_speech_tags, delimiters=delimiters) def get_keywords(self, num=6,", "获取最重要的num个长度大于等于word_min_len的关键词。 Args: num: window: word_min_len: page_rank_config: Returns: 关键词列表。AttriDict {} \"\"\" # 获取按照text rank的方式得到的关键词,并排序", "as nx import numpy as np from knlp.common.constant import sentence_delimiters, allow_speech_tags from knlp.information_extract.keywords_extraction.textrank", "# File Name: textrank_keyword # Author: <NAME> # Mail: <EMAIL> # Created Time:", "r in res: yield r for word_list in _edge_source: for w1, w2 in", "sort_words(vertex_source, edge_source, window=2, page_rank_config=None): \"\"\" 将单词按关键程度从大到小排序 Args: vertex_source: 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点 edge_source: 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边 window: 一个句子中相邻的window个单词,两两之间认为有边" ]
[ "self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\")", "multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source", "encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in", "groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\"", "class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args):", "!= \"csv\": raise Exception(\"Either of the output S3 lo cation provided is incorrect!\")", "source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source", "if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output", "+ source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as", "',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output", "'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index,", "\\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source", "\"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme", "S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as", "with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for", "= parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode", "open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index,", "self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme", "def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args =", "dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1]", "',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8')", "source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source +", "parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\":", "handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\":", "dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\":", "= json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter):", "'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index,", "= dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] !=", "import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def", "\\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source", "multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args", "self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise", "argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler()", "class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source", "parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode ==", "as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter)", "provided for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\") if __name__ == \"__main__\":", "multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source =", "urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or", "enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' +", "in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels +", "output S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8')", "GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else:", "= GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter)", "import json import argparse from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class", "def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename", "as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file):", "source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file,", "is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a',", "from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename =", "args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value", "of the output S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest',", "jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\")", "as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file):", "= GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url =", "handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode is invalid. Valid values are", "the output S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r',", "if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The", "open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index,", "main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args()", "dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output S3", "== \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided", "'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine", "label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset:", "incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8')", "handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise", "validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename =", "+ '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\", "Exception(\"Either of the output S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with", "jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name +", "in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"'", "labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' +", "\"csv\": raise Exception(\"Either of the output S3 lo cation provided is incorrect!\") def", "value provided for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\") if __name__ ==", "output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if", "= self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"')", "source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self,", "args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode is invalid.", "self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"')", "jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def", "GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri)", "+ source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\")", "json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser =", "for index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source =", "raise Exception(\"Either of the output S3 lo cation provided is incorrect!\") def read_write_multiclass_dataset(self):", "= argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler =", "args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1]", "enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"'", "'\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename,", "+ ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r',", "import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter()", "dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename)", "label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def", "= urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\"", "args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif", "from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object", "def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8')", "index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"')", "open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source =", "json.dumps(source).strip('\"') multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with", "or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output S3 lo cation provided", "cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\", "def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as", "json import argparse from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler:", "raise Exception(\"The value provided for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\") if", "urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename", "self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url", "= self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source +", "with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for", "+ '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri')", "open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source =", "GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri", "groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels,", "def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri =", "print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the", "!= \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output S3 lo", "= dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either", "__init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri", "Exception(\"The value provided for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\") if __name__", "multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing", "'\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter')", "\"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode is invalid. Valid values", "<reponame>rpivo/amazon-comprehend-examples import json import argparse from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter", "\"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output S3 lo cation", "urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object =", "source = json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main():", "parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode == \"MULTI_CLASS\": handler.read_write_multiclass_dataset()", "the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args)", "elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode is", "self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of the output S3 lo cation provided is", "+ ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the", "as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source", "lo cation provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file,", "source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode')", "dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme != \"s3\" or self.dataset_filename.split(\".\")[-1] != \"csv\": raise Exception(\"Either of", "provided is incorrect!\") def read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename,", "parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode ==", "else: raise Exception(\"The value provided for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\")", "'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine", "encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine)", "S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler = GroundTruthToCLRFormatConversionHandler() handler.validate_s3_input(args) if args.mode", "for mode is invalid. Valid values are MUTLI_CLASS|MULTI_LABEL\") if __name__ == \"__main__\": main()", "encoding='utf8') as multilabel_dataset: for index, jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine,", "= args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if", "multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a',", "import argparse from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def", "parser = argparse.ArgumentParser(description=\"Parsing the output S3Uri\") parser.add_argument('mode') parser.add_argument('dataset_output_S3Uri') parser.add_argument('label_delimiter') args = parser.parse_args() handler", "multiclass_dataset.write(class_name + ',\"' + source + '\"') multiclass_dataset.write(\"\\n\") def read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest',", "jsonLine in enumerate(groundtruth_output_file): labels, source = self.convert_object.convert_to_multilabel_dataset(index, jsonLine, label_delimiter) source = json.dumps(source).strip('\"') multilabel_dataset.write(labels", "dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme !=", "args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme = dataset_url.scheme self.dataset_filename = dataset_url.path.split(\"/\")[-1] print(self.dataset_filename) if dataset_scheme", "groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset: for index, jsonLine in enumerate(groundtruth_output_file): class_name,", "read_write_multilabel_dataset(self, label_delimiter): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as", "= \"\" def validate_s3_input(self, args): dataset_output_S3Uri = args.dataset_output_S3Uri dataset_url = urlparse(dataset_output_S3Uri) dataset_scheme =", "read_write_multiclass_dataset(self): with open('output.manifest', 'r', encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multiclass_dataset:", "= json.dumps(source).strip('\"') multilabel_dataset.write(labels + ',\"' + source + '\"') multilabel_dataset.write(\"\\n\") def main(): parser", "index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"') multiclass_dataset.write(class_name", "GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self): self.convert_object = GroundTruthToComprehendCLRFormatConverter() self.dataset_filename = \"\" def validate_s3_input(self,", "\"MULTI_CLASS\": handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for", "for index, jsonLine in enumerate(groundtruth_output_file): class_name, source = self.convert_object.convert_to_multiclass_dataset(index, jsonLine) source = json.dumps(source).strip('\"')", "encoding='utf-8') as groundtruth_output_file, \\ open(self.dataset_filename, 'a', encoding='utf8') as multilabel_dataset: for index, jsonLine in", "handler.read_write_multiclass_dataset() elif args.mode == \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode", "argparse from urllib.parse import urlparse from groundtruth_to_comprehend_clr_format_converter import GroundTruthToComprehendCLRFormatConverter class GroundTruthToCLRFormatConversionHandler: def __init__(self):", "== \"MULTI_LABEL\": handler.read_write_multilabel_dataset(args.label_delimiter) else: raise Exception(\"The value provided for mode is invalid. Valid" ]
[ "that they add up to a specific target. You may assume that each", "had been changed to zero-based indices. Please read the above updated description carefully.", "been changed to zero-based indices. Please read the above updated description carefully. '''", "assume that each input would have exactly one solution. Example: Given nums =", "would have exactly one solution. Example: Given nums = [2, 7, 11, 15],", "return format had been changed to zero-based indices. Please read the above updated", "Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].", ":rtype: List[int] \"\"\" d = {} for i, v in enumerate(nums): if target-v", "to a specific target. You may assume that each input would have exactly", "a specific target. You may assume that each input would have exactly one", "solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because", "integers, return indices of the two numbers such that they add up to", "Solution(object): def twoSum(self, nums, target): \"\"\" :type nums: List[int] :type target: int :rtype:", "[0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices.", "9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed to", "= [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] =", "for i, v in enumerate(nums): if target-v in d: return [d[target-v], i] d[v]", "int :rtype: List[int] \"\"\" d = {} for i, v in enumerate(nums): if", "***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ******************************************", "such that they add up to a specific target. You may assume that", "0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of", "nums, target): \"\"\" :type nums: List[int] :type target: int :rtype: List[int] \"\"\" d", "2016-09-02 ****************************************** ''' ''' Given an array of integers, return indices of the", "return [0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based", "one solution. Example: Given nums = [2, 7, 11, 15], target = 9,", "Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given", "(2016/2/13): The return format had been changed to zero-based indices. Please read the", "Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of integers,", "specific target. You may assume that each input would have exactly one solution.", "numbers such that they add up to a specific target. You may assume", "d = {} for i, v in enumerate(nums): if target-v in d: return", "carefully. ''' class Solution(object): def twoSum(self, nums, target): \"\"\" :type nums: List[int] :type", "nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE", "they add up to a specific target. You may assume that each input", "Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** '''", "target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,", "= 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return", "****************************************** ''' ''' Given an array of integers, return indices of the two", "target: int :rtype: List[int] \"\"\" d = {} for i, v in enumerate(nums):", "Please read the above updated description carefully. ''' class Solution(object): def twoSum(self, nums,", "<EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an", "coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time:", "You may assume that each input would have exactly one solution. Example: Given", "read the above updated description carefully. ''' class Solution(object): def twoSum(self, nums, target):", "i, v in enumerate(nums): if target-v in d: return [d[target-v], i] d[v] =", "UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read", "class Solution(object): def twoSum(self, nums, target): \"\"\" :type nums: List[int] :type target: int", "7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 +", "\"\"\" d = {} for i, v in enumerate(nums): if target-v in d:", "python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version:", "[2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2", "List[int] \"\"\" d = {} for i, v in enumerate(nums): if target-v in", "= 9, Because nums[0] + nums[1] = 2 + 7 = 9, return", "# -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1", "changed to zero-based indices. Please read the above updated description carefully. ''' class", "''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02", "of integers, return indices of the two numbers such that they add up", ":type target: int :rtype: List[int] \"\"\" d = {} for i, v in", "nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1]", "#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL>", "''' Given an array of integers, return indices of the two numbers such", "return indices of the two numbers such that they add up to a", "nums: List[int] :type target: int :rtype: List[int] \"\"\" d = {} for i,", "+ 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had", "Given an array of integers, return indices of the two numbers such that", "updated description carefully. ''' class Solution(object): def twoSum(self, nums, target): \"\"\" :type nums:", "''' ''' Given an array of integers, return indices of the two numbers", "add up to a specific target. You may assume that each input would", "utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04", ":type nums: List[int] :type target: int :rtype: List[int] \"\"\" d = {} for", "may assume that each input would have exactly one solution. Example: Given nums", "description carefully. ''' class Solution(object): def twoSum(self, nums, target): \"\"\" :type nums: List[int]", "11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7", "The return format had been changed to zero-based indices. Please read the above", "two numbers such that they add up to a specific target. You may", "9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0,", "2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of integers, return indices", "zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' '''", "have exactly one solution. Example: Given nums = [2, 7, 11, 15], target", "indices of the two numbers such that they add up to a specific", "the above updated description carefully. ''' class Solution(object): def twoSum(self, nums, target): \"\"\"", "target): \"\"\" :type nums: List[int] :type target: int :rtype: List[int] \"\"\" d =", "''' class Solution(object): def twoSum(self, nums, target): \"\"\" :type nums: List[int] :type target:", "1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please", "-*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created", "twoSum(self, nums, target): \"\"\" :type nums: List[int] :type target: int :rtype: List[int] \"\"\"", "each input would have exactly one solution. Example: Given nums = [2, 7,", "{} for i, v in enumerate(nums): if target-v in d: return [d[target-v], i]", "up to a specific target. You may assume that each input would have", "15], target = 9, Because nums[0] + nums[1] = 2 + 7 =", "zero-based indices. Please read the above updated description carefully. ''' class Solution(object): def", "array of integers, return indices of the two numbers such that they add", "= 9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed", "List[int] :type target: int :rtype: List[int] \"\"\" d = {} for i, v", "2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format", "format had been changed to zero-based indices. Please read the above updated description", "v in enumerate(nums): if target-v in d: return [d[target-v], i] d[v] = i", "Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0]", "Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of integers, return indices of", "nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The", "that each input would have exactly one solution. Example: Given nums = [2,", "of the two numbers such that they add up to a specific target.", "an array of integers, return indices of the two numbers such that they", "indices. Please read the above updated description carefully. ''' class Solution(object): def twoSum(self,", "above updated description carefully. ''' class Solution(object): def twoSum(self, nums, target): \"\"\" :type", "target. You may assume that each input would have exactly one solution. Example:", "def twoSum(self, nums, target): \"\"\" :type nums: List[int] :type target: int :rtype: List[int]", "Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array", "= {} for i, v in enumerate(nums): if target-v in d: return [d[target-v],", "Given nums = [2, 7, 11, 15], target = 9, Because nums[0] +", "\"\"\" :type nums: List[int] :type target: int :rtype: List[int] \"\"\" d = {}", "<filename>0001.Two Sum/solution.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh", "to zero-based indices. Please read the above updated description carefully. ''' class Solution(object):", "-*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-01-04 Last_modify:", "input would have exactly one solution. Example: Given nums = [2, 7, 11,", "7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had been", "the two numbers such that they add up to a specific target. You", "exactly one solution. Example: Given nums = [2, 7, 11, 15], target =", "Sum/solution.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email:", "Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of integers, return", "+ nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13):" ]
[ "N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1:", "10: (8, 2, GENERAL), 11: (9, 3, GENERAL), 12: (10, 1, GENERAL), }", "GENERAL), 9: (7, 1, GENERAL), 10: (8, 2, GENERAL), 11: (9, 3, GENERAL),", "2, ADMIN), 5: (3, 3, ADMIN), 6: (4, 1, ADMIN), 7: (5, 2,", "9: (7, 1, GENERAL), 10: (8, 2, GENERAL), 11: (9, 3, GENERAL), 12:", "2: (1, 2, GENERAL), 4: (3, 1, GENERAL), 3: (2, 2, ADMIN), 5:", "constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type", "tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4: (3, 1, GENERAL), 3:", "(4, 1, ADMIN), 7: (5, 2, GENERAL), 8: (6, 3, GENERAL), 9: (7,", "(7, 1, GENERAL), 10: (8, 2, GENERAL), 11: (9, 3, GENERAL), 12: (10,", "ADMIN), 5: (3, 3, ADMIN), 6: (4, 1, ADMIN), 7: (5, 2, GENERAL),", "TENANT_USERS = { 1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2:", "import constants N_USERS = 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL =", "constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN), # tenant_user_id:", "(5, 2, GENERAL), 8: (6, 3, GENERAL), 9: (7, 1, GENERAL), 10: (8,", "ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4: (3, 1,", "GENERAL), 8: (6, 3, GENERAL), 9: (7, 1, GENERAL), 10: (8, 2, GENERAL),", "3, ADMIN), 6: (4, 1, ADMIN), 7: (5, 2, GENERAL), 8: (6, 3,", "ADMIN), 7: (5, 2, GENERAL), 8: (6, 3, GENERAL), 9: (7, 1, GENERAL),", "= 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1,", "ADMIN), 6: (4, 1, ADMIN), 7: (5, 2, GENERAL), 8: (6, 3, GENERAL),", "4: (3, 1, GENERAL), 3: (2, 2, ADMIN), 5: (3, 3, ADMIN), 6:", "api.common import constants N_USERS = 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL", "(3, 3, ADMIN), 6: (4, 1, ADMIN), 7: (5, 2, GENERAL), 8: (6,", "3: (2, 2, ADMIN), 5: (3, 3, ADMIN), 6: (4, 1, ADMIN), 7:", "(1, 2, GENERAL), 4: (3, 1, GENERAL), 3: (2, 2, ADMIN), 5: (3,", "GENERAL), 10: (8, 2, GENERAL), 11: (9, 3, GENERAL), 12: (10, 1, GENERAL),", "1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL),", "(1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4:", "ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN),", "1, GENERAL), 10: (8, 2, GENERAL), 11: (9, 3, GENERAL), 12: (10, 1,", "11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = {", "8: (6, 3, GENERAL), 9: (7, 1, GENERAL), 10: (8, 2, GENERAL), 11:", "= constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN), #", "N_USERS = 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS", "5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1,", "<reponame>daichi-yoshikawa/django-boilerplate<filename>core/management/commands/constants.py<gh_stars>1-10 from api.common import constants N_USERS = 11 N_TENANTS = 5 ADMIN =", "GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN), # tenant_user_id: user_id,", "1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4: (3,", "user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4: (3, 1, GENERAL), 3: (2,", "tenant_id, role_type 2: (1, 2, GENERAL), 4: (3, 1, GENERAL), 3: (2, 2,", "6: (4, 1, ADMIN), 7: (5, 2, GENERAL), 8: (6, 3, GENERAL), 9:", "= constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS = { 1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id,", "5: (3, 3, ADMIN), 6: (4, 1, ADMIN), 7: (5, 2, GENERAL), 8:", "1, ADMIN), 7: (5, 2, GENERAL), 8: (6, 3, GENERAL), 9: (7, 1,", "= 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value TENANT_USERS =", "(2, 2, ADMIN), 5: (3, 3, ADMIN), 6: (4, 1, ADMIN), 7: (5,", "{ 1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1, 2,", "# tenant_user_id: user_id, tenant_id, role_type 2: (1, 2, GENERAL), 4: (3, 1, GENERAL),", "1, GENERAL), 3: (2, 2, ADMIN), 5: (3, 3, ADMIN), 6: (4, 1,", "7: (5, 2, GENERAL), 8: (6, 3, GENERAL), 9: (7, 1, GENERAL), 10:", "from api.common import constants N_USERS = 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value", "2, GENERAL), 4: (3, 1, GENERAL), 3: (2, 2, ADMIN), 5: (3, 3,", "GENERAL), 4: (3, 1, GENERAL), 3: (2, 2, ADMIN), 5: (3, 3, ADMIN),", "(3, 1, GENERAL), 3: (2, 2, ADMIN), 5: (3, 3, ADMIN), 6: (4,", "constants N_USERS = 11 N_TENANTS = 5 ADMIN = constants.TENANT_USER_ROLE_TYPE.ADMIN.value GENERAL = constants.TENANT_USER_ROLE_TYPE.GENERAL.value", "= { 1: (1, 1, ADMIN), # tenant_user_id: user_id, tenant_id, role_type 2: (1,", "GENERAL), 3: (2, 2, ADMIN), 5: (3, 3, ADMIN), 6: (4, 1, ADMIN),", "2, GENERAL), 8: (6, 3, GENERAL), 9: (7, 1, GENERAL), 10: (8, 2,", "role_type 2: (1, 2, GENERAL), 4: (3, 1, GENERAL), 3: (2, 2, ADMIN),", "3, GENERAL), 9: (7, 1, GENERAL), 10: (8, 2, GENERAL), 11: (9, 3,", "(6, 3, GENERAL), 9: (7, 1, GENERAL), 10: (8, 2, GENERAL), 11: (9," ]
[ "= [0.04, 0.5] epsilon_list = [0.1] # scaling_list = [0.5, .01] # alpha", "alpha = 0 # scaling_list = [0.5, 0.01] # alpha = 0.25 max_reward_adapt", "in scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1,", "'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' : 10,", "0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01", "env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04,", "= np.arange(start=0, stop=1, step=epsilon) # # agent_list = [] # for _ in", "numpy as np from agents import pendulum_agent from eNet_Agent import eNet from eNet_Agent", "alpha = 1 # scaling_list = [1, .4] # alpha = 0 #", "epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug'", "= [0.04, 0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5]", "agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp =", "max_reward_e_net = curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon # dt_net", "[5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1] # scaling_list = [0.5,", "= experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] >", "parameters to be used in the experiment''' epLen = 200 nEps = 2000", "= [0.5, .01] # alpha = 1 # scaling_list = [1, .4] #", "opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count = 0 # TRYING OUT EACH", "OPTIMAL ONE for scaling in scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed':", "ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon)", "be used in the experiment''' epLen = 200 nEps = 2000 numIters =", "# # del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING DATA", "# del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING DATA TO", "curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon # dt_net = dt_net_data", "curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling", "from src import agent import pickle ''' Defining parameters to be used in", "dt_net_data # # del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING", "= exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling", "= dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR", "= 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR", "adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0]", "0 # scaling_list = [0.5, 0.01] # alpha = 0.25 max_reward_adapt = 0", "= experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data() # #", "# del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING DATA TO CSV #dt_adapt.to_csv('pendulum_adapt.csv') #dt_net.to_csv('pendulum_net_1.csv')", "# state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list = [] # for", "experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0]", "agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING DATA TO CSV #dt_adapt.to_csv('pendulum_adapt.csv')", "from eNet_Agent import eNetPendulum from src import environment from src import experiment from", ".01] # alpha = 1 # scaling_list = [1, .4] # alpha =", "np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list =", "= exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: #", "0.99, scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run()", "= 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count =", "nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data =", "import gym import numpy as np from agents import pendulum_agent from eNet_Agent import", "# # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _ in", "0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if", "0.01 count = 0 # TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE", "# opt_epsilon_scaling = epsilon # dt_net = dt_net_data # # del agent_list #", "scaling_list = [0.04, 0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list = [0.04,", "# dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward >", "[0.5, 0.01] # alpha = 0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling", "for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp", "used in the experiment''' epLen = 200 nEps = 2000 numIters = 50", "eNet_Discount from eNet_Agent import eNetPendulum from src import environment from src import experiment", "import eNetPendulum from src import environment from src import experiment from src import", "nEps = 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING", "EXPERIMENT FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) # state_net", "RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen,", "= 1 # scaling_list = [1, .4] # alpha = 0 # scaling_list", "import eNet_Discount from eNet_Agent import eNetPendulum from src import environment from src import", "dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1,", ": 10, 'numIters' : numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap", "save=True) # exp.run() # dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] #", "exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net", "# action_net = np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) #", "count = 0 # TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE for", "eNet from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from src import environment", "ONE for scaling in scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed': 1,", "= [1, .4] # alpha = 0 # scaling_list = [0.5, 0.01] #", "gym import numpy as np from agents import pendulum_agent from eNet_Agent import eNet", "import experiment from src import agent import pickle ''' Defining parameters to be", "= 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count = 0 # TRYING", "= 0.01 count = 0 # TRYING OUT EACH SCALING FACTOR FOR OPTIMAL", "PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list =", "0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count = 0 # TRYING OUT", "'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters}", "'deBug' : False, 'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters} # #", "agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True)", "# RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon)", "FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling,", "curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward #", "= 200 nEps = 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) #####", "10, 'numIters' : numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap =", "False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] #", "'numIters' : numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = []", "= agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM", "src import environment from src import experiment from src import agent import pickle", "epLen = 200 nEps = 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False)", "as np from agents import pendulum_agent from eNet_Agent import eNet from eNet_Agent import", "experiment from src import agent import pickle ''' Defining parameters to be used", "= [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1] # scaling_list =", "= {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps,", "# for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # #", "np.arange(start=0, stop=1, step=epsilon) # # agent_list = [] # for _ in range(numIters):", "0.01] # alpha = 0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling =", "exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling =", "Defining parameters to be used in the experiment''' epLen = 200 nEps =", "#scaling_list = [0.04, 0.5] epsilon_list = [0.1] # scaling_list = [0.5, .01] #", "to be used in the experiment''' epLen = 200 nEps = 2000 numIters", "opt_e_net_scaling = 0.01 count = 0 # TRYING OUT EACH SCALING FACTOR FOR", "max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del", "opt_epsilon_scaling = epsilon # dt_net = dt_net_data # # del agent_list # del", "import pendulum_agent from eNet_Agent import eNet from eNet_Agent import eNet_Discount from eNet_Agent import", "OUT EACH SCALING FACTOR FOR OPTIMAL ONE for scaling in scaling_list: for epsilon", "# exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data()", "2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE", "# scaling_list = [1, .4] # alpha = 0 # scaling_list = [0.5,", "= 0.01 opt_e_net_scaling = 0.01 count = 0 # TRYING OUT EACH SCALING", "ALGORITHM agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp", "in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig =", "# TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE for scaling in scaling_list:", ": numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for", "dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net:", "eNetPendulum from src import environment from src import experiment from src import agent", "the experiment''' epLen = 200 nEps = 2000 numIters = 50 env =", "[1, .4] # alpha = 0 # scaling_list = [0.5, 0.01] # alpha", "# # agent_list = [] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net,", "# scaling_list = [0.5, 0.01] # alpha = 0.25 max_reward_adapt = 0 max_reward_e_net", "1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' : 10, 'numIters' :", "from agents import pendulum_agent from eNet_Agent import eNet from eNet_Agent import eNet_Discount from", "AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list", "scaling_list = [1, .4] # alpha = 0 # scaling_list = [0.5, 0.01]", "1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' :", "##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list", "experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data() # # curr_reward", "range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run()", "= scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data #", "del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) # SAVING DATA TO CSV", "environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045]", "# RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _ in range(numIters):", "stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list = []", "(dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling =", "agents import pendulum_agent from eNet_Agent import eNet from eNet_Agent import eNet_Discount from eNet_Agent", "scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() #", "stop=1, step=epsilon) # # agent_list = [] # for _ in range(numIters): #", "agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data", "np from agents import pendulum_agent from eNet_Agent import eNet from eNet_Agent import eNet_Discount", "from src import experiment from src import agent import pickle ''' Defining parameters", "eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from src import environment from src", "from eNet_Agent import eNet from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from", "scaling_list = [0.5, .01] # alpha = 1 # scaling_list = [1, .4]", "0.01 opt_e_net_scaling = 0.01 count = 0 # TRYING OUT EACH SCALING FACTOR", "action_net = np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) # #", "'recFreq' : 10, 'numIters' : numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM", "ADAPTIVE ALGORITHM agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995))", "> max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list =", "opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET", "range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list,", "# dt_net = dt_net_data # # del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling)", "scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data()", "if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data", "= np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list", "in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp = experiment.Experiment(env,", "exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data() #", "# max_reward_e_net = curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon #", "max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count = 0 #", "= 0 # TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE for scaling", "alpha = 0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling", "50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list =", "scaling in scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' :", "experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt:", "= (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap", "0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1] # scaling_list = [0.5, .01]", "experiment''' epLen = 200 nEps = 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen,", "numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT", "FACTOR FOR OPTIMAL ONE for scaling in scaling_list: for epsilon in epsilon_list: experiment_dict", "TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list = [5,", "(3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data", "scaling_list = [0.5, 0.01] # alpha = 0.25 max_reward_adapt = 0 max_reward_e_net =", "for scaling in scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq'", "scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING", ".4] # alpha = 0 # scaling_list = [0.5, 0.01] # alpha =", "scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1] # scaling_list", "= 0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling =", ": 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' : 10, 'numIters'", "dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON", "del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0,", "[] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) #", "(dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del", "{'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq'", "src import experiment from src import agent import pickle ''' Defining parameters to", "= exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt", "step=epsilon) # # agent_list = [] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net,", "# agent_list = [] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99,", "# exp.run() # dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if", "import eNet from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from src import", "import agent import pickle ''' Defining parameters to be used in the experiment'''", "max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon", "# if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling = scaling", "[0.04, 0.5] epsilon_list = [0.1] # scaling_list = [0.5, .01] # alpha =", "[0.04, 0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list", "<reponame>Gjain234/AdaptiveQLearning import gym import numpy as np from agents import pendulum_agent from eNet_Agent", "step=epsilon) # state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list = [] #", "import environment from src import experiment from src import agent import pickle '''", "agent_list = [] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling,", "0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count = 0", "pendulum_agent from eNet_Agent import eNet from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum", "_ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp =", "EACH SCALING FACTOR FOR OPTIMAL ONE for scaling in scaling_list: for epsilon in", "[] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap,", "epsilon # dt_net = dt_net_data # # del agent_list # del dt_net_data #print(opt_adapt_scaling)", "numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _", "FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list = [5, 0.6]", "state_net = np.arange(start=0, stop=1, step=epsilon) # # agent_list = [] # for _", "nEps, 'recFreq' : 10, 'numIters' : numIters} # # RUNNING EXPERIMENT FOR ADAPTIVE", "= 0 # scaling_list = [0.5, 0.01] # alpha = 0.25 max_reward_adapt =", "(dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list", "max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap", "scaling # opt_epsilon_scaling = epsilon # dt_net = dt_net_data # # del agent_list", "# # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) # exp.run() # dt_net_data =", "'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters} # # RUNNING EXPERIMENT FOR", "scaling_list: for epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath':", "eNet_Agent import eNetPendulum from src import environment from src import experiment from src", "''' Defining parameters to be used in the experiment''' epLen = 200 nEps", "# scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1] #", "state_net, 0.99, scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict, save=True) #", "if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling = scaling #", "# alpha = 0.25 max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01", "experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False, 'nEps':", "environment from src import experiment from src import agent import pickle ''' Defining", "_ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig", "# opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon # dt_net = dt_net_data #", "# scaling_list = [0.5, .01] # alpha = 1 # scaling_list = [1,", "in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' :", "# alpha = 1 # scaling_list = [1, .4] # alpha = 0", "experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt =", "src import agent import pickle ''' Defining parameters to be used in the", "0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list =", "import pickle ''' Defining parameters to be used in the experiment''' epLen =", "TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE for scaling in scaling_list: for", "> max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling =", "RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) #", "FOR EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) # state_net =", "del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net", "exp.run() # dt_net_data = exp.save_data() # # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward", "[0.5, .01] # alpha = 1 # scaling_list = [1, .4] # alpha", "max_reward_adapt = 0 max_reward_e_net = 0 opt_adapt_scaling = 0.01 opt_e_net_scaling = 0.01 count", "dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling", "dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT", "= 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list", "exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt = (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] opt_adapt_scaling = scaling dt_adapt =", "False, 'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters} # # RUNNING EXPERIMENT", "exp = experiment.Experiment(env, agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0]", "= dt_net_data # # del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling) #", "pickle ''' Defining parameters to be used in the experiment''' epLen = 200", "import numpy as np from agents import pendulum_agent from eNet_Agent import eNet from", "SCALING FACTOR FOR OPTIMAL ONE for scaling in scaling_list: for epsilon in epsilon_list:", "EXPERIMENT FOR ADAPTIVE ALGORITHM agent_list_adap = [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps,", "= [0.5, 0.01] # alpha = 0.25 max_reward_adapt = 0 max_reward_e_net = 0", "= [] for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env,", "agent_list, experiment_dict, save=True) # exp.run() # dt_net_data = exp.save_data() # # curr_reward =", "0.045] # scaling_list = [5, 0.6] #scaling_list = [0.04, 0.5] epsilon_list = [0.1]", "agent_list_adap del agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM #", "= [] # for _ in range(numIters): # agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1)))", "= (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward # opt_e_net_scaling", "= curr_reward # opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon # dt_net =", "opt_e_net_scaling = scaling # opt_epsilon_scaling = epsilon # dt_net = dt_net_data # #", "= scaling # opt_epsilon_scaling = epsilon # dt_net = dt_net_data # # del", "eNet_Agent import eNet from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from src", "# curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net = curr_reward", "agent_list_adap del dt_adapt_data # RUNNING EXPERIMENT FOR EPSILON NET ALGORITHM # action_net =", "agent_list_adap, experiment_dict) adap_fig = exp.run() dt_adapt_data = exp.save_data() if (dt_adapt_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] > max_reward_adapt: max_reward_adapt", "opt_adapt_scaling = scaling dt_adapt = dt_adapt_data opt_adapt_agent_list = agent_list_adap del agent_list_adap del dt_adapt_data", "from src import environment from src import experiment from src import agent import", "0.5] epsilon_list = [0.1] # scaling_list = [0.5, .01] # alpha = 1", "for epsilon in epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv',", "for _ in range(numIters): agent_list_adap.append(pendulum_agent.PendulumAgent(epLen, nEps, scaling, 0.995)) exp = experiment.Experiment(env, agent_list_adap, experiment_dict)", "dt_net = dt_net_data # # del agent_list # del dt_net_data #print(opt_adapt_scaling) #print(opt_epsilon_scaling) #print(opt_e_net_scaling)", "0 # TRYING OUT EACH SCALING FACTOR FOR OPTIMAL ONE for scaling in", "EPSILON NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0,", "in the experiment''' epLen = 200 nEps = 2000 numIters = 50 env", "= [0.1] # scaling_list = [0.5, .01] # alpha = 1 # scaling_list", "1 # scaling_list = [1, .4] # alpha = 0 # scaling_list =", "FOR OPTIMAL ONE for scaling in scaling_list: for epsilon in epsilon_list: experiment_dict =", "# agent_list.append(eNet_Discount(action_net, state_net, 0.99, scaling, (3,1))) # # exp = experiment.Experiment(env, agent_list, experiment_dict,", "epsilon_list = [0.1] # scaling_list = [0.5, .01] # alpha = 1 #", "agent import pickle ''' Defining parameters to be used in the experiment''' epLen", "200 nEps = 2000 numIters = 50 env = environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER", "[0.1] # scaling_list = [0.5, .01] # alpha = 1 # scaling_list =", "= environment.make_pendulumEnvironment(epLen, False) ##### PARAMETER TUNING FOR AMBULANCE ENVIRONMENT scaling_list = [0.04, 0.035,", "= epsilon # dt_net = dt_net_data # # del agent_list # del dt_net_data", "from eNet_Agent import eNet_Discount from eNet_Agent import eNetPendulum from src import environment from", "ENVIRONMENT scaling_list = [0.04, 0.035, 0.045] # scaling_list = [5, 0.6] #scaling_list =", "epsilon_list: experiment_dict = {'seed': 1, 'epFreq' : 1, 'targetPath': './tmp.csv', 'deBug' : False,", ": False, 'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters} # # RUNNING", "'./tmp.csv', 'deBug' : False, 'nEps': nEps, 'recFreq' : 10, 'numIters' : numIters} #", "# # curr_reward = (dt_net_data.groupby(['episode']).mean().tail(1))['epReward'].iloc[0] # if curr_reward > max_reward_e_net: # max_reward_e_net =", "# alpha = 0 # scaling_list = [0.5, 0.01] # alpha = 0.25", "NET ALGORITHM # action_net = np.arange(start=0, stop=1, step=epsilon) # state_net = np.arange(start=0, stop=1," ]
[ "key,result in results.items(): assert result is not None assert 'failure' not in result['response'].keys()", "import pytest import os from ..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\"", "fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert", "failure for valid hosts for key,result in results.items(): assert result is not None", "= http.get_requests_batch(lines) assert results is not None # assert no failure for valid", "= \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line = line.rstrip('\\n')", "to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n')", "failure for inValid Hosts for key, result in results.items(): assert result is not", "[line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines) #assert result is not None", "not None # assert failure for inValid Hosts for key, result in results.items():", "\"\"\" test if _get_http_request(args...) returns failure for an invalid url. \"\"\" file_name =", "\"\"\" test if _get_http_request(args..) returns valid contents from a valid url. \"\"\" file_name", "test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of valid domain name is", "domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name,", "#file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for line in", "is not None assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test", "= http.get_requests_batch(lines) assert results is not None # assert failure for inValid Hosts", "test if _get_http_request(args...) returns failure for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\"", "assert no failure for valid hosts for key,result in results.items(): assert result is", "\"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line", "in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of", "test _get_http_request(arg...) primitive when a list of invaid domain name is passed to", "= http._get_http_request(line) assert res is not None assert 'failure' in res['response'].keys() fd.close() def", "http._get_http_request(line) assert res is not None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self):", "\"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for line", "in fd] #result = http.get_requests_batch(lines) #assert result is not None #assert 'error' in", "= http.get_requests_batch(lines) #assert result is not None #assert 'error' in result #assert result['error']", "'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes long", "'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list", "\"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line", "= http._get_http_request(line) assert res is not None assert 'failure' not in res['response'].keys() fd.close()", "http._get_http_request(line) assert res is not None assert 'failure' not in res['response'].keys() fd.close() def", "\"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line", "finish TODO: choose url that gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd", "'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a", "res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents from a", "if _get_http_request(args..) returns valid contents from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\"", "None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns", "not None assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if", "a list of invaid domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name =", "None assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive", "for valid hosts for key,result in results.items(): assert result is not None assert", "for key, result in results.items(): assert result is not None assert 'failure' in", "def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of invaid domain name", "that gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines", "invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in", "thread takes long time to finish TODO: choose url that gives thread error", "to finish TODO: choose url that gives thread error \"\"\" #file_name = \"data/input_file.txt\"", "# assert no failure for valid hosts for key,result in results.items(): assert result", "failure for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r')", "invaid domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd =", "def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for an invalid url. \"\"\"", "file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line =", "#result = http.get_requests_batch(lines) #assert result is not None #assert 'error' in result #assert", "fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results =", "\"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results", "test _get_http_request(arg...) primitive when a list of valid domain name is passed to", "is not None # assert no failure for valid hosts for key,result in", "None # assert no failure for valid hosts for key,result in results.items(): assert", "http.get_requests_batch(lines) assert results is not None # assert failure for inValid Hosts for", "def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents from a valid url.", "test if _get_http_request(args..) returns valid contents from a valid url. \"\"\" file_name =", "name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r')", "http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for an", "'r') lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert results", "_get_http_request(arg...) primitive when a list of invaid domain name is passed to get_requests_batch(args...).", "for line in fd] results = http.get_requests_batch(lines) assert results is not None #", "open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert", "result in results.items(): assert result is not None assert 'failure' in result['response'].keys() fd.close()", "thread error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n')", "\"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for line in fd] #result", "gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines =", "for line in fd] #result = http.get_requests_batch(lines) #assert result is not None #assert", "#assert result is not None #assert 'error' in result #assert result['error'] is \"Threads", "line in fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert res is not", "None #assert 'error' in result #assert result['error'] is \"Threads took too long to", "assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a", "fd = open(file_name, 'r') for line in fd: line = line.rstrip('\\n') res =", "is not None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...)", "result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes long time to finish", "line in fd] #result = http.get_requests_batch(lines) #assert result is not None #assert 'error'", "assert res is not None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\"", "invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in", "TODO: choose url that gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd =", "in fd] results = http.get_requests_batch(lines) assert results is not None # assert no", "in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes long time to", "test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for an invalid url. \"\"\" file_name", "is not None # assert failure for inValid Hosts for key, result in", "results is not None # assert failure for inValid Hosts for key, result", "#assert 'error' in result #assert result['error'] is \"Threads took too long to finish.\"", "open(file_name, 'r') #lines = [line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines) #assert", "from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for", "valid contents from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name,", "assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid", "assert results is not None # assert failure for inValid Hosts for key,", "def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of valid domain name", "fd] results = http.get_requests_batch(lines) assert results is not None # assert no failure", "assert res is not None assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self):", "= \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd]", "pytest import os from ..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test", "lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert results is", "passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines =", "returns failure for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name,", "def test_batch_url_thread_error(self): \"\"\" test if thread takes long time to finish TODO: choose", "returns valid contents from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd =", "assert failure for inValid Hosts for key, result in results.items(): assert result is", "fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of valid domain", "test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents from a valid url. \"\"\"", "in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of", "error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for", "'error' in result #assert result['error'] is \"Threads took too long to finish.\" #fd.close()", "no failure for valid hosts for key,result in results.items(): assert result is not", "line in fd] results = http.get_requests_batch(lines) assert results is not None # assert", "fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes long time to finish TODO:", "\"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line = line.rstrip('\\n') res", "= open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines)", "primitive when a list of valid domain name is passed to get_requests_batch(args...). \"\"\"", "result is not None assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\"", "open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert", "= line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert 'failure' in", "res is not None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test", "\"\"\" test _get_http_request(arg...) primitive when a list of invaid domain name is passed", "\"\"\" test _get_http_request(arg...) primitive when a list of valid domain name is passed", "domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name,", "results.items(): assert result is not None assert 'failure' not in result['response'].keys() fd.close() def", "get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for", "_get_http_request(arg...) primitive when a list of valid domain name is passed to get_requests_batch(args...).", "results is not None # assert no failure for valid hosts for key,result", "for key,result in results.items(): assert result is not None assert 'failure' not in", "import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for", "= [line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines) #assert result is not", "# assert failure for inValid Hosts for key, result in results.items(): assert result", "\"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results", "name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r')", "is not None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if", "get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for", "[line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert results is not None", "http.get_requests_batch(lines) #assert result is not None #assert 'error' in result #assert result['error'] is", "an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line", "fd] results = http.get_requests_batch(lines) assert results is not None # assert failure for", "in results.items(): assert result is not None assert 'failure' in result['response'].keys() fd.close() def", "http.get_requests_batch(lines) assert results is not None # assert no failure for valid hosts", "if _get_http_request(args...) returns failure for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd", "test if thread takes long time to finish TODO: choose url that gives", "Hosts for key, result in results.items(): assert result is not None assert 'failure'", "not None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive", "not None assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...)", "in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents from", "not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list", "url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for line in fd:", "from ..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns", "of valid domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd", "is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines", "results = http.get_requests_batch(lines) assert results is not None # assert no failure for", "passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines =", "list of valid domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\"", "'r') for line in fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert res", "assert result is not None assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self):", "time to finish TODO: choose url that gives thread error \"\"\" #file_name =", "for inValid Hosts for key, result in results.items(): assert result is not None", "= \"data/input_file.txt\" #fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for line in fd]", "open(file_name, 'r') for line in fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert", "TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for an invalid url.", "= open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines)", "when a list of valid domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name", "res = http._get_http_request(line) assert res is not None assert 'failure' in res['response'].keys() fd.close()", "= \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd]", "long time to finish TODO: choose url that gives thread error \"\"\" #file_name", "contents from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r')", "key, result in results.items(): assert result is not None assert 'failure' in result['response'].keys()", "class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure for an invalid", "when a list of invaid domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name", "url that gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name, 'r')", "valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in", "fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of invaid domain", "not None # assert no failure for valid hosts for key,result in results.items():", "line = line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert 'failure'", "in fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert res is not None", "valid domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd =", "takes long time to finish TODO: choose url that gives thread error \"\"\"", "not None #assert 'error' in result #assert result['error'] is \"Threads took too long", "assert result is not None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\"", "result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of valid", "..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...) returns failure", "= open(file_name, 'r') for line in fd: line = line.rstrip('\\n') res = http._get_http_request(line)", "_get_http_request(args...) returns failure for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd =", "_get_http_request(args..) returns valid contents from a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd", "fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents from a valid", "fd] #result = http.get_requests_batch(lines) #assert result is not None #assert 'error' in result", "result is not None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test", "res is not None assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\"", "is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines", "is not None #assert 'error' in result #assert result['error'] is \"Threads took too", "\"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd = open(invalid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line", "fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in fd] results =", "line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert 'failure' not in", "in results.items(): assert result is not None assert 'failure' not in result['response'].keys() fd.close()", "inValid Hosts for key, result in results.items(): assert result is not None assert", "= open(file_name, 'r') #lines = [line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines)", "a list of valid domain name is passed to get_requests_batch(args...). \"\"\" valid_hosts_file_name =", "valid hosts for key,result in results.items(): assert result is not None assert 'failure'", "assert 'failure' not in res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when", "import os from ..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if", "for an invalid url. \"\"\" file_name = \"data/invalid_hosts.txt\" fd = open(file_name, 'r') for", "list of invaid domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\"", "= line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert 'failure' not", "test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of invaid domain name is", "'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..) returns valid contents", "= [line.rstrip('\\n') for line in fd] results = http.get_requests_batch(lines) assert results is not", "None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when", "choose url that gives thread error \"\"\" #file_name = \"data/input_file.txt\" #fd = open(file_name,", "of invaid domain name is passed to get_requests_batch(args...). \"\"\" invalid_hosts_file_name = \"data/invalid_hosts.txt\" fd", "valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n') for line in", "assert results is not None # assert no failure for valid hosts for", "'r') #lines = [line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines) #assert result", "res = http._get_http_request(line) assert res is not None assert 'failure' not in res['response'].keys()", "in fd] results = http.get_requests_batch(lines) assert results is not None # assert failure", "None assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread", "is not None assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test", "line.rstrip('\\n') res = http._get_http_request(line) assert res is not None assert 'failure' in res['response'].keys()", "results = http.get_requests_batch(lines) assert results is not None # assert failure for inValid", "test_batch_url_thread_error(self): \"\"\" test if thread takes long time to finish TODO: choose url", "if thread takes long time to finish TODO: choose url that gives thread", "for line in fd: line = line.rstrip('\\n') res = http._get_http_request(line) assert res is", "None # assert failure for inValid Hosts for key, result in results.items(): assert", "#lines = [line.rstrip('\\n') for line in fd] #result = http.get_requests_batch(lines) #assert result is", "not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes long time", "file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line =", "hosts for key,result in results.items(): assert result is not None assert 'failure' not", "assert 'failure' not in result['response'].keys() fd.close() def test_batch_url_thread_error(self): \"\"\" test if thread takes", "#fd = open(file_name, 'r') #lines = [line.rstrip('\\n') for line in fd] #result =", "url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in fd:", "result is not None #assert 'error' in result #assert result['error'] is \"Threads took", "not None assert 'failure' in res['response'].keys() fd.close() def test_url_exist(self): \"\"\" test if _get_http_request(args..)", "\"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line = line.rstrip('\\n') res", "os from ..primitives import http class TestHTTPMethods: def test_url_not_exist(self): \"\"\" test if _get_http_request(args...)", "\"\"\" test if thread takes long time to finish TODO: choose url that", "a valid url. \"\"\" file_name = \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line", "primitive when a list of invaid domain name is passed to get_requests_batch(args...). \"\"\"", "= \"data/valid_hosts.txt\" fd = open(file_name, 'r') for line in fd: line = line.rstrip('\\n')", "results.items(): assert result is not None assert 'failure' in result['response'].keys() fd.close() def test_batch_url_valid_hosts(self):", "res['response'].keys() fd.close() def test_batch_url_invalid_hosts(self): \"\"\" test _get_http_request(arg...) primitive when a list of invaid", "to get_requests_batch(args...). \"\"\" valid_hosts_file_name = \"data/valid_hosts.txt\" fd = open(valid_hosts_file_name, 'r') lines = [line.rstrip('\\n')" ]
[ "models from models.fan_model import FAN from utils.evaluation import get_preds, final_preds from faceboxes import", ", rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0])", "of saving pics to gen gif SAVE = False SAVE_DIR = \"./save_pics\" if", "img_ori = cap.read() # rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if", "os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap = cv2.VideoCapture(0) while True:", "/ 2.0, d[3] - (d[3] - d[1]) / 2.0]) # center[1] = center[1]", "center[1] + (d[3] - d[1]) * 0.12 hw = max(d[2] - d[0], d[3]", "model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if", "(d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)),", "- d[1]) * 0.12 hw = max(d[2] - d[0], d[3] - d[1]) scale", "gif SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please specify", "# center[1] = center[1] + (d[3] - d[1]) * 0.12 hw = max(d[2]", "\"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen gif SAVE = False SAVE_DIR", "= final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img)", "for name in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model", "# rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects) == 0:", "storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model =", "run model...\") exit(0) model_names = sorted( name for name in models.__dict__ if name.islower()", "while True: _, img_ori = cap.read() # rects = face_detector(img_ori, 1) rects =", "_, img_ori = cap.read() # rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector)", "(pts[0], pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]),", "d[3] - (d[3] - d[1]) / 2.0]) # center[1] = center[1] + (d[3]", "output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64]) #", "face_detector = face_detector_init(proto, mdl) if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count", "rects = detect(img_ori, face_detector) if len(rects) == 0: continue print(rects) for rect in", "FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage,", "[scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in", "if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1]", "and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\":", "specify run model...\") exit(0) model_names = sorted( name for name in models.__dict__ if", "64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts", "rect.right() + 10, rect.bottom() + 10] # d = [rect.left() , rect.top() ,", "= \"./save_pics\" if len(sys.argv) < 2: print(\"please specify run model...\") exit(0) model_names =", "= torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto,", "models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if", "d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR,", "LS3DW import models from models.fan_model import FAN from utils.evaluation import get_preds, final_preds from", "\"./save_pics\" if len(sys.argv) < 2: print(\"please specify run model...\") exit(0) model_names = sorted(", "import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen", "center = torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3] -", "* from datasets import W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model import", "(d[3] - d[1]) * 0.12 hw = max(d[2] - d[0], d[3] - d[1])", "if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc:", "CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen gif SAVE =", "and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict()", "= output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64])", "datasets import W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model import FAN from", "cap.read() # rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects) ==", "name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\": model_dict =", "inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\":", "import copy import sys from utils.imutils import * from utils.transforms import * from", "reference_scale = 200 cap = cv2.VideoCapture(0) while True: _, img_ori = cap.read() #", "import torchvision.transforms as transforms import numpy as np import cv2 import copy import", "utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" #", "center[1] = center[1] + (d[3] - d[1]) * 0.12 hw = max(d[2] -", "torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k]", "from utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\"", "range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1, 2)", "from utils.transforms import * from datasets import W300LP, VW300, AFLW2000, LS3DW import models", "if len(sys.argv) < 2: print(\"please specify run model...\") exit(0) model_names = sorted( name", "255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)), img_ori) cv2.waitKey(1) count +=", "FAN from utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH =", "for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255,", "float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp", "model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE", "faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to", "rects: d = [rect.left() - 10, rect.top() - 10, rect.right() + 10, rect.bottom()", "d[1]) * 0.12 hw = max(d[2] - d[0], d[3] - d[1]) scale =", "= pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0],", "checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector =", "d = [rect.left() , rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] -", "False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please specify run model...\") exit(0)", "= [rect.left() - 10, rect.top() - 10, rect.right() + 10, rect.bottom() + 10]", "\"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE == True: if", "os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap = cv2.VideoCapture(0) while True: _,", "checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')]", "True: _, img_ori = cap.read() # rects = face_detector(img_ori, 1) rects = detect(img_ori,", "model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl =", "= cap.read() # rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects)", "= np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if", "/ reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp =", "pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori,", "name in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model =", "for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda()", "model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in", ", rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3] -", "not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap = cv2.VideoCapture(0) while", "img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0)", "+ 10, rect.bottom() + 10] # d = [rect.left() , rect.top() , rect.right()", "= 200 cap = cv2.VideoCapture(0) while True: _, img_ori = cap.read() # rects", "# d = [rect.left() , rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2]", "inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map", "* 0.12 hw = max(d[2] - d[0], d[3] - d[1]) scale = float(hw", "len(rects) == 0: continue print(rects) for rect in rects: d = [rect.left() -", "rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3]", "== True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap", "score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64,", "1) rects = detect(img_ori, face_detector) if len(rects) == 0: continue print(rects) for rect", "model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict'])", "import torch import torchvision.transforms as transforms import numpy as np import cv2 import", "import numpy as np import cv2 import copy import sys from utils.imutils import", "print(rects) for rect in rects: d = [rect.left() - 10, rect.top() - 10,", "= 0 reference_scale = 200 cap = cv2.VideoCapture(0) while True: _, img_ori =", "cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)), img_ori) cv2.waitKey(1) count += 1", "exit(0) model_names = sorted( name for name in models.__dict__ if name.islower() and not", "(d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True:", "= cv2.VideoCapture(0) while True: _, img_ori = cap.read() # rects = face_detector(img_ori, 1)", "= torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1])", "[64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]):", "face_detector_init(proto, mdl) if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0", "reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans,", "import models from models.fan_model import FAN from utils.evaluation import get_preds, final_preds from faceboxes", "flag of saving pics to gen gif SAVE = False SAVE_DIR = \"./save_pics\"", "utils.transforms import * from datasets import W300LP, VW300, AFLW2000, LS3DW import models from", "as transforms import numpy as np import cv2 import copy import sys from", "= output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img =", "== 0: continue print(rects) for rect in rects: d = [rect.left() - 10,", "model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.',", "loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model", "pics to gen gif SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv) <", "if len(rects) == 0: continue print(rects) for rect in rects: d = [rect.left()", "d[1]) scale = float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans =", "torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl)", "cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE ==", "print(\"please specify run model...\") exit(0) model_names = sorted( name for name in models.__dict__", "'')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval()", "not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\": model_dict", "torch import torchvision.transforms as transforms import numpy as np import cv2 import copy", "= checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto", "- (d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0])", "proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE ==", "import * from utils.transforms import * from datasets import W300LP, VW300, AFLW2000, LS3DW", "[center], [scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i", "d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0]) # center[1] =", "rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3]", "from utils.imutils import * from utils.transforms import * from datasets import W300LP, VW300,", "np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]),", "copy import sys from utils.imutils import * from utils.transforms import * from datasets", "import FAN from utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH", "/ 2.0]) # center[1] = center[1] + (d[3] - d[1]) * 0.12 hw", "== \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for", "model = FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH,", "10, rect.right() + 10, rect.bottom() + 10] # d = [rect.left() , rect.top()", "crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\": score_map =", "cv2 import copy import sys from utils.imutils import * from utils.transforms import *", "= crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\": score_map", "AFLW2000, LS3DW import models from models.fan_model import FAN from utils.evaluation import get_preds, final_preds", "score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img", "model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img", "sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map,", "final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for", "+ (d[3] - d[1]) * 0.12 hw = max(d[2] - d[0], d[3] -", "if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap = cv2.VideoCapture(0)", "if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale =", "= model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu()", "rect.bottom() + 10] # d = [rect.left() , rect.top() , rect.right() , rect.bottom()]", "d[3] - d[1]) scale = float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1])", "gen gif SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please", "in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint =", "k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint", "from models.fan_model import FAN from utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init,", "mdl) if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale", "face_detector) if len(rects) == 0: continue print(rects) for rect in rects: d =", "0.12 hw = max(d[2] - d[0], d[3] - d[1]) scale = float(hw /", "else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl", "import sys from utils.imutils import * from utils.transforms import * from datasets import", "# print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center,", "scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data else:", "10, rect.top() - 10, rect.right() + 10, rect.bottom() + 10] # d =", "cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2],", "import W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model import FAN from utils.evaluation", "= FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda", "max(d[2] - d[0], d[3] - d[1]) scale = float(hw / reference_scale) # print(scale)", "= \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE == True:", "= face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects) == 0: continue print(rects)", "face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects) == 0: continue print(rects) for", "continue print(rects) for rect in rects: d = [rect.left() - 10, rect.top() -", "d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)), img_ori)", "* from utils.transforms import * from datasets import W300LP, VW300, AFLW2000, LS3DW import", "checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH)", "print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint =", "i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0),", "- d[1]) scale = float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans", "(d[3] - d[1]) / 2.0]) # center[1] = center[1] + (d[3] - d[1])", "saving pics to gen gif SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv)", "cv2.VideoCapture(0) while True: _, img_ori = cap.read() # rects = face_detector(img_ori, 1) rects", "\"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k", "as np import cv2 import copy import sys from utils.imutils import * from", "= np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0],", "in rects: d = [rect.left() - 10, rect.top() - 10, rect.right() + 10,", "- 10, rect.right() + 10, rect.bottom() + 10] # d = [rect.left() ,", "face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen gif", "detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen gif SAVE", "output = model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map =", "storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict) else:", "print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i]", "import * from datasets import W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model", "[rect.left() , rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] -", "= float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1))", "if sys.argv[1] == \"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img =", "print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0,", "= copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output", "mdl = \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE == True: if not", "+ 10] # d = [rect.left() , rect.top() , rect.right() , rect.bottom()] center", "in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2)", "< 2: print(\"please specify run model...\") exit(0) model_names = sorted( name for name", "sys from utils.imutils import * from utils.transforms import * from datasets import W300LP,", "= False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please specify run model...\")", "checkpoint[k] model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto =", "map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] = checkpoint[k] model.load_state_dict(model_dict)", "2.0, d[3] - (d[3] - d[1]) / 2.0]) # center[1] = center[1] +", "- d[0], d[3] - d[1]) scale = float(hw / reference_scale) # print(scale) img_chn", "= model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys():", "from datasets import W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model import FAN", "transforms import numpy as np import cv2 import copy import sys from utils.imutils", "200 cap = cv2.VideoCapture(0) while True: _, img_ori = cap.read() # rects =", "W300LP, VW300, AFLW2000, LS3DW import models from models.fan_model import FAN from utils.evaluation import", "(d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0]) #", ", rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0,", "model...\") exit(0) model_names = sorted( name for name in models.__dict__ if name.islower() and", "SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please specify run", "= center[1] + (d[3] - d[1]) * 0.12 hw = max(d[2] - d[0],", "= torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\"", "0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori)", "torch.FloatTensor([d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1]) /", "torchvision.transforms as transforms import numpy as np import cv2 import copy import sys", "10] # d = [rect.left() , rect.top() , rect.right() , rect.bottom()] center =", "else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img)", "[rect.left() - 10, rect.top() - 10, rect.right() + 10, rect.bottom() + 10] #", "2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255,", "= face_detector_init(proto, mdl) if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count =", "count = 0 reference_scale = 200 cap = cv2.VideoCapture(0) while True: _, img_ori", "d[1]) / 2.0]) # center[1] = center[1] + (d[3] - d[1]) * 0.12", "for rect in rects: d = [rect.left() - 10, rect.top() - 10, rect.right()", "img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp)", "rect.top() - 10, rect.right() + 10, rect.bottom() + 10] # d = [rect.left()", "# print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2,", "to gen gif SAVE = False SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2:", "sorted( name for name in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name]))", "pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori,", "0 reference_scale = 200 cap = cv2.VideoCapture(0) while True: _, img_ori = cap.read()", "copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output =", "(255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)), img_ori) cv2.waitKey(1)", "in range(pts_img.shape[0]): pts = pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1,", "rects = face_detector(img_ori, 1) rects = detect(img_ori, face_detector) if len(rects) == 0: continue", "import get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag", "2.0]) # center[1] = center[1] + (d[3] - d[1]) * 0.12 hw =", "# flag of saving pics to gen gif SAVE = False SAVE_DIR =", "= torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict'] for k in checkpoint.keys(): model_dict[k.replace('module.', '')] =", "utils.imutils import * from utils.transforms import * from datasets import W300LP, VW300, AFLW2000,", "get_preds, final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of", "255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\",", "VW300, AFLW2000, LS3DW import models from models.fan_model import FAN from utils.evaluation import get_preds,", "detect(img_ori, face_detector) if len(rects) == 0: continue print(rects) for rect in rects: d", "model.load_state_dict(model_dict) else: model = torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\"", "= max(d[2] - d[0], d[3] - d[1]) scale = float(hw / reference_scale) #", "2: print(\"please specify run model...\") exit(0) model_names = sorted( name for name in", "= sorted( name for name in models.__dict__ if name.islower() and not name.startswith(\"__\") and", "torch.nn.DataParallel(model).cuda() checkpoint = torch.load(CHECKPOINT_PATH) model.load_state_dict(checkpoint['state_dict']) model.eval() proto = \"faceboxes_deploy.prototxt\" mdl = \"faceboxes_iter_120000.caffemodel\" face_detector", "from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics", "print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale)", "== \"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center],", "numpy as np import cv2 import copy import sys from utils.imutils import *", "name for name in models.__dict__ if name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names)", "<reponame>lippman1125/pytorch_FAN import torch import torchvision.transforms as transforms import numpy as np import cv2", "pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255,", "0: continue print(rects) for rect in rects: d = [rect.left() - 10, rect.top()", "pts_img = final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy()) #", "= detect(img_ori, face_detector) if len(rects) == 0: continue print(rects) for rect in rects:", "import cv2 import copy import sys from utils.imutils import * from utils.transforms import", "rect in rects: d = [rect.left() - 10, rect.top() - 10, rect.right() +", "(0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255))", "SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200", "d = [rect.left() - 10, rect.top() - 10, rect.right() + 10, rect.bottom() +", "\"cpu\": score_map = output[-1].data else: score_map = output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale],", "hw = max(d[2] - d[0], d[3] - d[1]) scale = float(hw / reference_scale)", "- d[1]) / 2.0]) # center[1] = center[1] + (d[3] - d[1]) *", "callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint", "models.fan_model import FAN from utils.evaluation import get_preds, final_preds from faceboxes import face_detector_init, detect", "SAVE_DIR = \"./save_pics\" if len(sys.argv) < 2: print(\"please specify run model...\") exit(0) model_names", "np import cv2 import copy import sys from utils.imutils import * from utils.transforms", "2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE", "= [rect.left() , rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2]", "rect.top() , rect.right() , rect.bottom()] center = torch.FloatTensor([d[2] - (d[2] - d[0]) /", "255, 255)) cv2.imshow(\"landmark\", img_ori) if SAVE == True: cv2.imwrite(os.path.join(SAVE_DIR, \"image_{}.jpg\".format(count)), img_ori) cv2.waitKey(1) count", "= \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving pics to gen gif SAVE = False", "\"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE == True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR)", "output[-1].data.cpu() pts_img = final_preds(score_map, [center], [scale], [64, 64]) # print(pts_img) pts_img = np.squeeze(pts_img.numpy())", "# print(pts_img) pts_img = np.squeeze(pts_img.numpy()) # print(pts_img) for i in range(pts_img.shape[0]): pts =", "- 10, rect.top() - 10, rect.right() + 10, rect.bottom() + 10] # d", "final_preds from faceboxes import face_detector_init, detect CHECKPOINT_PATH = \"./checkpoint/fan3d_wo_norm_att/model_best.pth.tar\" # flag of saving", "(2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] ==", "-1, 2) cv2.rectangle(img_ori, (d[0], d[1]), (d[2], d[3]), (255, 255, 255)) cv2.imshow(\"landmark\", img_ori) if", "center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1] == \"cpu\": score_map = output[-1].data", "= \"faceboxes_iter_120000.caffemodel\" face_detector = face_detector_init(proto, mdl) if SAVE == True: if not os.path.exists(SAVE_DIR):", "len(sys.argv) < 2: print(\"please specify run model...\") exit(0) model_names = sorted( name for", "sys.argv[1] == \"cpu\": model_dict = model.state_dict() checkpoint = torch.load(CHECKPOINT_PATH, map_location=lambda storage, loc: storage)['state_dict']", "pts_img[i] cv2.circle(img_ori, (pts[0], pts[1]), 2, (0, 255, 0), -1, 2) cv2.rectangle(img_ori, (d[0], d[1]),", "d[0], d[3] - d[1]) scale = float(hw / reference_scale) # print(scale) img_chn =", "scale = float(hw / reference_scale) # print(scale) img_chn = copy.deepcopy(img_ori[:,:,::-1]) img_trans = np.transpose(img_chn,", "- (d[3] - d[1]) / 2.0]) # center[1] = center[1] + (d[3] -", "np.transpose(img_chn, (2,0,1)) inp = crop(img_trans, center, scale) inp.unsqueeze_(0) output = model(inp) if sys.argv[1]", "cap = cv2.VideoCapture(0) while True: _, img_ori = cap.read() # rects = face_detector(img_ori,", "10, rect.bottom() + 10] # d = [rect.left() , rect.top() , rect.right() ,", "True: if not os.path.exists(SAVE_DIR): os.mkdir(SAVE_DIR) count = 0 reference_scale = 200 cap =", "- d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0]) # center[1]", "name.islower() and not name.startswith(\"__\") and callable(models.__dict__[name])) print(model_names) model = FAN(2) if sys.argv[1] ==", "model_names = sorted( name for name in models.__dict__ if name.islower() and not name.startswith(\"__\")" ]
[ "string return cap_string def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class", "symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for symb in listSymb: succes =", "there, then the symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\")", "CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico +", "LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i +", "= Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self, filename): pil_image = Image.open(filename)", "+ \"/\" def read(self, filename): # Extract symbol from targetted captcha symb_extractor =", "f[0].isdigit(): cap_string += f[0] else: cap_string += f[3] break if not succes: #", "nb_unread += 1 #return the string return cap_string def compare(self, symb_np, im_dic): #print", "filename): # mat_pix is a numpy array mat_pix = self.openImage(filename) list_im = []", "read(self, filename): # Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb =", "i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i + 1) *", "im = Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self, filename): pil_image =", "def read(self, filename): # Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb", "im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename):", "f[0] else: cap_string += f[3] break if not succes: # If you go", "you go there, then the symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread)", "* (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i + 1) * (LETTER_SIZE", "= folderDico + \"/\" def read(self, filename): # Extract symbol from targetted captcha", "if not succes: # If you go there, then the symbol has not", "+ (i + 1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19,", "def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def read(self, filename):", "Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if", "return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def", "numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string += f[0] else:", "PIL import Image import numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE =", "return cap_string def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object):", "LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT", "symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def", "import os,sys from PIL import Image import numpy LETTER_NB = 5 LETTER_SPACE =", "LETTER_LEFT + (i + 1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb =", "os,sys from PIL import Image import numpy LETTER_NB = 5 LETTER_SPACE = 1", "CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def read(self,", "from PIL import Image import numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE", "left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self, filename):", "# Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string", "self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string += f[0] else: cap_string +=", "a numpy array mat_pix = self.openImage(filename) list_im = [] for i in range(5):", "= [] for i in range(5): left = LETTER_LEFT + i * (LETTER_SIZE", "if f[0].isdigit(): cap_string += f[0] else: cap_string += f[3] break if not succes:", "in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if", "list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self, filename): pil_image", "1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring", "is a numpy array mat_pix = self.openImage(filename) list_im = [] for i in", "for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is a", "f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image)", "read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1 #return the string return", "+ \".png\") nb_unread += 1 #return the string return cap_string def compare(self, symb_np,", "= 0 for symb in listSymb: succes = False for f in os.listdir(self.folderDico):", "succes = False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico +", "dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string +=", "Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self, filename): pil_image = Image.open(filename) return", "captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is a numpy", "= 8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\"", "= \"\" nb_unread = 0 for symb in listSymb: succes = False for", "def extractSymbol(self, filename): # mat_pix is a numpy array mat_pix = self.openImage(filename) list_im", "succes = True if f[0].isdigit(): cap_string += f[0] else: cap_string += f[3] break", "the symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread +=", "+ LETTER_SPACE) right = LETTER_LEFT + (i + 1) * (LETTER_SIZE + LETTER_SPACE)", "= numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string += f[0]", "nb_unread = 0 for symb in listSymb: succes = False for f in", "go there, then the symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) +", "= 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico):", "[] for i in range(5): left = LETTER_LEFT + i * (LETTER_SIZE +", "(LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i + 1) * (LETTER_SIZE +", "+= 1 #return the string return cap_string def compare(self, symb_np, im_dic): #print symb_np", "self).__init__() def extractSymbol(self, filename): # mat_pix is a numpy array mat_pix = self.openImage(filename)", "filename): # Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename)", "self.folderDico = folderDico + \"/\" def read(self, filename): # Extract symbol from targetted", "+ LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im", "left = LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT +", "= True if f[0].isdigit(): cap_string += f[0] else: cap_string += f[3] break if", "listSymb: succes = False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico", "str(nb_unread) + \".png\") nb_unread += 1 #return the string return cap_string def compare(self,", "def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for", "16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico =", "8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def", "dic_symb): succes = True if f[0].isdigit(): cap_string += f[0] else: cap_string += f[3]", "1 symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return", "symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return list_im", "then the symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread", "= 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico", "mat_pix = self.openImage(filename) list_im = [] for i in range(5): left = LETTER_LEFT", "\"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\"", "# If you go there, then the symbol has not been read Image.fromarray(symb).save(\"error/symb\"", "# mat_pix is a numpy array mat_pix = self.openImage(filename) list_im = [] for", "numpy array mat_pix = self.openImage(filename) list_im = [] for i in range(5): left", "cap_string = \"\" nb_unread = 0 for symb in listSymb: succes = False", "__init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def read(self, filename): #", "1 #return the string return cap_string def compare(self, symb_np, im_dic): #print symb_np return", "mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return list_im def openImage(self,", "super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is a numpy array mat_pix =", "\"/\" def read(self, filename): # Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor()", "+ 1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb)", "* (LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im =", "in range(5): left = LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right =", "extractSymbol(self, filename): # mat_pix is a numpy array mat_pix = self.openImage(filename) list_im =", "+ str(nb_unread) + \".png\") nb_unread += 1 #return the string return cap_string def", "+ f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if f[0].isdigit():", "= LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i", "+= f[0] else: cap_string += f[3] break if not succes: # If you", "im = im.convert('1') return list_im def openImage(self, filename): pil_image = Image.open(filename) return numpy.array(pil_image)", "Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1 #return the string return cap_string", "range(5): left = LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT", "class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): #", "= 1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object):", "folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def read(self, filename): # Extract", "cap_string def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring", "from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread", "def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is a numpy array", "\"\" nb_unread = 0 for symb in listSymb: succes = False for f", "for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def", "f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes", "import numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT =", "If you go there, then the symbol has not been read Image.fromarray(symb).save(\"error/symb\" +", "(i + 1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right]", "LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for", "else: cap_string += f[3] break if not succes: # If you go there,", "= Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True", "captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0", "= LETTER_LEFT + (i + 1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb", "folderDico + \"/\" def read(self, filename): # Extract symbol from targetted captcha symb_extractor", "5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT = 16", "(LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255)", "break if not succes: # If you go there, then the symbol has", "#return the string return cap_string def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np,", "targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread =", "im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self):", "symb in listSymb: succes = False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image", "\"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is", "= 5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT =", "0 for symb in listSymb: succes = False for f in os.listdir(self.folderDico): if", "in listSymb: succes = False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image =", "i in range(5): left = LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE) right", "+= f[3] break if not succes: # If you go there, then the", "cap_string += f[3] break if not succes: # If you go there, then", "\".png\") nb_unread += 1 #return the string return cap_string def compare(self, symb_np, im_dic):", "self.openImage(filename) list_im = [] for i in range(5): left = LETTER_LEFT + i", "if self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string += f[0] else: cap_string", "not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1 #return the", "pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes =", "f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb): succes = True if f[0].isdigit(): cap_string", "True if f[0].isdigit(): cap_string += f[0] else: cap_string += f[3] break if not", "numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self,", "f[3] break if not succes: # If you go there, then the symbol", "compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\"", "symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for", "symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\"", "10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader,", "False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb", "listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for symb in listSymb:", "symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__()", "right = LETTER_LEFT + (i + 1) * (LETTER_SIZE + LETTER_SPACE) - 1", "captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for symb in", "numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT = 10", "super(CaptchaReader, self).__init__() self.folderDico = folderDico + \"/\" def read(self, filename): # Extract symbol", "#print symb_np return numpy.array_equal(symb_np, im_dic/255) class captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor,", "cap_string += f[0] else: cap_string += f[3] break if not succes: # If", "symbol has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1", "LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT = 10 LETTER_RIGHT = 16 class", "LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im =", "succes: # If you go there, then the symbol has not been read", "captchaSymbolExtractor(object): \"\"\"docstring for captchaSymbolExtractor\"\"\" def __init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix", "__init__(self): super(captchaSymbolExtractor, self).__init__() def extractSymbol(self, filename): # mat_pix is a numpy array mat_pix", "been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1 #return the string", "Extract symbol from targetted captcha symb_extractor = captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string =", "= mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1') return list_im def", "import Image import numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE = 8", "not succes: # If you go there, then the symbol has not been", "LETTER_LEFT = 10 LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self,", "has not been read Image.fromarray(symb).save(\"error/symb\" + str(nb_unread) + \".png\") nb_unread += 1 #return", "for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb =", "= self.openImage(filename) list_im = [] for i in range(5): left = LETTER_LEFT +", "Image import numpy LETTER_NB = 5 LETTER_SPACE = 1 LETTER_SIZE = 8 LETTER_LEFT", "LETTER_SPACE) right = LETTER_LEFT + (i + 1) * (LETTER_SIZE + LETTER_SPACE) -", "for i in range(5): left = LETTER_LEFT + i * (LETTER_SIZE + LETTER_SPACE)", "+ i * (LETTER_SIZE + LETTER_SPACE) right = LETTER_LEFT + (i + 1)", "if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb, dic_symb):", "mat_pix is a numpy array mat_pix = self.openImage(filename) list_im = [] for i", "os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f) dic_symb = numpy.array(pil_image) if self.compare(symb,", "= False for f in os.listdir(self.folderDico): if f.endswith(\".png\"): pil_image = Image.open(self.folderDico + f)", "- 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im = Image.fromarray(symb*255) im = im.convert('1')", "= symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for symb in listSymb: succes", "array mat_pix = self.openImage(filename) list_im = [] for i in range(5): left =", "class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__() self.folderDico = folderDico", "1) * (LETTER_SIZE + LETTER_SPACE) - 1 symb = mat_pix[6:19, left:right] list_im.append(symb) im", "= captchaSymbolExtractor() listSymb = symb_extractor.extractSymbol(filename) cap_string = \"\" nb_unread = 0 for symb", "for symb in listSymb: succes = False for f in os.listdir(self.folderDico): if f.endswith(\".png\"):", "list_im = [] for i in range(5): left = LETTER_LEFT + i *", "self).__init__() self.folderDico = folderDico + \"/\" def read(self, filename): # Extract symbol from", "the string return cap_string def compare(self, symb_np, im_dic): #print symb_np return numpy.array_equal(symb_np, im_dic/255)", "LETTER_RIGHT = 16 class CaptchaReader(object): \"\"\"docstring for CaptchaReader\"\"\" def __init__(self, folderDico): super(CaptchaReader, self).__init__()" ]
[ "ranking for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) + \" \\tRank: \"", "[] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped", "i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) + \" \\tRank: \" + str(rank[i][1]))", "0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1])", "[] processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in", "= [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show()", "the page fanking factors and then assign ranking to each nodes base on", "return(initial_pageRank) #sorts the page fanking factors and then assign ranking to each nodes", "page fanking factors and then assign ranking to each nodes base on its", "def adj_nodes(G): list_nodes_info = [] node_mapped = [] i = 0 for u", "[] node_mapped = [] i = 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes", "page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for i", "while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index", "range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR =", "adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking", "to each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for", "= i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = []", "list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along", "initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking factors and then assign ranking", "i = 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count =", "on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]])", "i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0 for", "each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i", "for i in range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index =", "0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0 for", "i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G)", "+ (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking factors and", "nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G =", "list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def", "matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped = []", "the nodes along with ranking for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0])", "#sorts the page fanking factors and then assign ranking to each nodes base", "= [] count = 0 for v in G.nodes(): if G.has_edge(u,v)==True: count =", "<NAME>, <NAME>, <NAME> \"\"\" import networkx as netx import matplotlib.pyplot as plt #find", "with ranking for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) + \" \\tRank:", "netx import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped", "netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints", "list_nodes_info = [] node_mapped = [] i = 0 for u in G.nodes():", "def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info))", "= 0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR +", "then assign ranking to each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks", "list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking", "rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for i in range(len(G.nodes())):", "processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking factors and then assign", "the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for", "u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0 for v in", "for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))):", "return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank =", "plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped = [] i =", "= 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0", "count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns", "\"\"\" import networkx as netx import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G):", "node_mapped = [] i = 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes =", "assign ranking to each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks =", "ranking to each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = []", "= adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with", "in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0 for j", "for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR)", "node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the", "as netx import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = []", "= node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts", "in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0 for v in G.nodes():", "cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page", "along with ranking for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) + \"", "= page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for i", "page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for i in", "= ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for i in range(len(G.nodes())): print(\"Node:", "in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i", "v in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u))", "networkx as netx import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info =", "= processed_pageRank return(initial_pageRank) #sorts the page fanking factors and then assign ranking to", "range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G", "list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped):", "importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking", "range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank", "\"\"\" @author: <NAME>, <NAME>, <NAME> \"\"\" import networkx as netx import matplotlib.pyplot as", "G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i =", "@author: <NAME>, <NAME>, <NAME> \"\"\" import networkx as netx import matplotlib.pyplot as plt", "#find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped = [] i = 0", "in range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR", "count = 0 for v in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v))", "node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank", "processed_pageRank return(initial_pageRank) #sorts the page fanking factors and then assign ranking to each", "adj_nodes(G): list_nodes_info = [] node_mapped = [] i = 0 for u in", "plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes", "#prints the nodes along with ranking for i in range(len(G.nodes())): print(\"Node: \" +", "for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped =", "for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0 for v", "import networkx as netx import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info", "page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)):", "factors and then assign ranking to each nodes base on its importance def", "its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True)", "<filename>Assignment_1/git/CSL622/rankingNodes.py \"\"\" @author: <NAME>, <NAME>, <NAME> \"\"\" import networkx as netx import matplotlib.pyplot", "nodes along with ranking for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) +", "<NAME>, <NAME> \"\"\" import networkx as netx import matplotlib.pyplot as plt #find adjacent_nodes", "ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for i in", "netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the", "= 0 for v in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u))", "nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph())", "nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for", "i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank =", "return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank", "ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12)", "for i in range(len(G.nodes())): print(\"Node: \" + str(rank[i][0]) + \" \\tRank: \" +", "G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank =", "= [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR", "= [] node_mapped = [] i = 0 for u in G.nodes(): list_nodes_info.append([])", "nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in", "for v in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes)", "#returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = []", "cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking factors", "count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page", "G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped)", "0 for v in G.nodes(): if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count)", "i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank", "ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped)", "import matplotlib.pyplot as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped =", "(initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking factors and then", "i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]])", "= [] i = 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = []", "base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())):", "= netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info)", "range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0 for j in", "in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor", "= count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the", "ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = []", "processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)):", "[] count = 0 for v in G.nodes(): if G.has_edge(u,v)==True: count = count+1", "and then assign ranking to each nodes base on its importance def ranking_assign(G,pageRank_factor,list_nodes_info):", "in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank =", "factor def page_rank(G,list_nodes_info,node_mapped): initial_pageRank = [] processed_pageRank = [] for i in range(len(list_nodes_info)):", "in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in (range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking)", "[] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR =", "[] i = 0 for u in G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count", "(range(len(G.nodes()))): ranking.append([i+1,list_nodes_info[i][0]]) return(ranking) G = netx.read_edgelist(r\"pagerank.txt\",create_using=netx.DiGraph()) netx.draw_spring(G,with_labels=1,node_size=200,font_size=12) plt.show() list_nodes_info,node_mapped = adj_nodes(G) pageRank_factor =", "= [] processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i", "node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank)", "def ranking_assign(G,pageRank_factor,list_nodes_info): nodes_with_ranks = [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking =", "[] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i in", "if G.has_edge(u,v)==True: count = count+1 list_adjNodes.append(int(v)) list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1", "list_nodes_info.append([]) list_adjNodes = [] count = 0 for v in G.nodes(): if G.has_edge(u,v)==True:", "i in range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j])", "list_nodes_info[i].append(int(u)) list_nodes_info[i].append(count) list_nodes_info[i].append(list_adjNodes) node_mapped.insert(i,int(u)) i = i+1 return(list_nodes_info,node_mapped) #returns the page ranking factor", "= [] for i in range(len(G.nodes())): nodes_with_ranks.insert(i,[pageRank_factor[i],list_nodes_info[i][0]]) nodes_with_ranks.sort(reverse=True) ranking = [] for i", "<NAME> \"\"\" import networkx as netx import matplotlib.pyplot as plt #find adjacent_nodes def", "initial_pageRank = [] processed_pageRank = [] for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for", "pageRank_factor = page_rank(G,list_nodes_info,node_mapped) rank = ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for", "G.nodes(): list_nodes_info.append([]) list_adjNodes = [] count = 0 for v in G.nodes(): if", "list_adjNodes = [] count = 0 for v in G.nodes(): if G.has_edge(u,v)==True: count", "j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank", "for i in range(len(list_nodes_info)): initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0", "as plt #find adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped = [] i", "= cumPR + (initial_pageRank[node_index]/list_nodes_info[node_index][1]) processed_pageRank.insert(i,cumPR) initial_pageRank = processed_pageRank return(initial_pageRank) #sorts the page fanking", "cumPR = 0 for j in range(len(list_nodes_info[i][2])): node_index = node_mapped.index(list_nodes_info[i][2][j]) cumPR = cumPR", "adjacent_nodes def adj_nodes(G): list_nodes_info = [] node_mapped = [] i = 0 for", "fanking factors and then assign ranking to each nodes base on its importance", "ranking_assign(G,pageRank_factor,list_nodes_info) #prints the nodes along with ranking for i in range(len(G.nodes())): print(\"Node: \"", "initial_pageRank.insert(i,1/len(list_nodes_info)) while(len(set(initial_pageRank))!=len(initial_pageRank)): for i in range(len(list_nodes_info)): cumPR = 0 for j in range(len(list_nodes_info[i][2])):" ]
[ "and the following disclaimer in the documentation # and/or other materials provided with", "assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def", "assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on()", "callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True)", "wificontrol import WiFiControl @pytest.fixture def ssid(): network = { 'ssid': 'Test' } return", "IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.", "self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1", "self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert", "<<EMAIL>> # # Copyright (c) 2016, Emlid Limited # All rights reserved. #", "def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count", "False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting", "# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, #", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "in binary form must reproduce the above copyright notice, # this list of", "Redistribution and use in source and binary forms, # with or without modification,", "self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self):", "self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status()", "All rights reserved. # # Redistribution and use in source and binary forms,", "assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started =", "from wificontrol import WiFiControl @pytest.fixture def ssid(): network = { 'ssid': 'Test' }", "== 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True", "test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert", "retain the above copyright notice, # this list of conditions and the following", "= False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect =", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT", "assert status == ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None)", "== 1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert", "name of the copyright holder nor the names of its contributors # may", "HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #", "is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY", "state, status = self.manager.get_status() assert state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value", "1 def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if", "# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL", "== 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started =", "self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result, callback,", "assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value", "assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count ==", "self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert", "Limited # All rights reserved. # # Redistribution and use in source and", "provided that the following conditions are met: # # 1. Redistributions of source", "assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count ==", "assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi()", "1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True)", "FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE", "ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "mock.Mock(return_value=True) state, status = self.manager.get_status() assert state == self.manager.HOST_STATE assert status is None", "test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if args: callback({},", "self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name)", "are met: # # 1. Redistributions of source code must retain the above", "self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "and/or other materials provided with the distribution. # # 3. Neither the name", "Neither the name of the copyright holder nor the names of its contributors", "test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert", "2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1", "self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is", "with or without modification, # are permitted provided that the following conditions are", "self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started =", "self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert", "== 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66'", "permitted provided that the following conditions are met: # # 1. Redistributions of", "forms, # with or without modification, # are permitted provided that the following", "its contributors # may be used to endorse or promote products derived from", "mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count ==", "} return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock()", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE", "assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count ==", "1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1", "= mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager", "self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT,", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status", "= False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state == self.manager.WPA_STATE", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY", "self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count", "self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1", "def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count ==", "mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count ==", "== 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count ==", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES", "mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count ==", "self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:]", "(c) 2016, Emlid Limited # All rights reserved. # # Redistribution and use", "# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE", "PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "following conditions are met: # # 1. Redistributions of source code must retain", "True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False)", "self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started", "# # 1. Redistributions of source code must retain the above copyright notice,", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT,", "disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright", "self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True)", "callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1", "== 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result, callback, args,", "assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert", "self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self,", "state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False", "DAMAGE. import pytest import mock from wificontrol import WiFiControl @pytest.fixture def ssid(): network", "CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR", "== 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count ==", "ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args)", "names of its contributors # may be used to endorse or promote products", "pytest import mock from wificontrol import WiFiControl @pytest.fixture def ssid(): network = {", "def ssid(): network = { 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def", "class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode()", "= name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name)", "self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started", "def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started", "None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status =", "# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR", "*args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid,", "used to endorse or promote products derived from this software # without specific", "THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot =", "def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1", "LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED #", "self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self):", "or promote products derived from this software # without specific prior written permission.", "1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "= self.manager.get_status() assert state == self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid):", "NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR", "USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF", "# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert", "following disclaimer. # # 2. Redistributions in binary form must reproduce the above", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR", "reproduce the above copyright notice, # this list of conditions and the following", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR", "TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA,", "use in source and binary forms, # with or without modification, # are", "promote products derived from this software # without specific prior written permission. #", "(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "of source code must retain the above copyright notice, # this list of", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert", "or without modification, # are permitted provided that the following conditions are met:", "0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid)", "self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state ==", "THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF", "== 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip()", "Redistributions of source code must retain the above copyright notice, # this list", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert state ==", "mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:])", "start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1", "assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value", "self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan()", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest import mock from", "= False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started =", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "Emlid Limited # All rights reserved. # # Redistribution and use in source", "and binary forms, # with or without modification, # are permitted provided that", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR", "self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count", "without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "= False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid)", "def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args) else:", "notice, # this list of conditions and the following disclaimer. # # 2.", "== 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started", "OF SUCH DAMAGE. import pytest import mock from wificontrol import WiFiControl @pytest.fixture def", "NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF", "met: # # 1. Redistributions of source code must retain the above copyright", "= True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started =", "3. Neither the name of the copyright holder nor the names of its", "MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO", "== ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started =", "1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1", "copyright notice, # this list of conditions and the following disclaimer in the", "the copyright holder nor the names of its contributors # may be used", "self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count", "ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True)", "== 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def", "assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert", "SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result,", "rights reserved. # # Redistribution and use in source and binary forms, #", "of its contributors # may be used to endorse or promote products derived", "= start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count ==", "self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value", "mock from wificontrol import WiFiControl @pytest.fixture def ssid(): network = { 'ssid': 'Test'", "0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self,", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, #", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS", "distribution. # # 3. Neither the name of the copyright holder nor the", "2016, Emlid Limited # All rights reserved. # # Redistribution and use in", "= mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count", "0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0", "== 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name()", "1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert", "this list of conditions and the following disclaimer in the documentation # and/or", "of conditions and the following disclaimer in the documentation # and/or other materials", "== 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting()", "assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def", "self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test'", "list of conditions and the following disclaimer in the documentation # and/or other", "= mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count ==", "def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started", "# are permitted provided that the following conditions are met: # # 1.", "conditions and the following disclaimer. # # 2. Redistributions in binary form must", "= mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1", "WiFiControl @pytest.fixture def ssid(): network = { 'ssid': 'Test' } return network class", "# this list of conditions and the following disclaimer in the documentation #", "FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class", "self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status =", "1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert", "self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1", "= self.manager.get_status() assert state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True", "conditions are met: # # 1. Redistributions of source code must retain the", "callback, args, timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started", "BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1", "self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count == 1 assert self.manager.wpasupplicant.get_p2p_name.call_count", "= FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert", "assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert", "self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started", "# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY", "self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count", "copyright notice, # this list of conditions and the following disclaimer. # #", "OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY", "mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self):", "self.manager.get_status() assert state == self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid): def", "# Written by <NAME> and <NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid", "source and binary forms, # with or without modification, # are permitted provided", "self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value =", "1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid)", "self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert", "assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None,", "PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "= mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count == 1 assert self.manager.wpasupplicant.get_p2p_name.call_count ==", "# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY,", "args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert", "OF THE POSSIBILITY OF SUCH DAMAGE. import pytest import mock from wificontrol import", "test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT", "self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name)", "self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started", "assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def", "self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid)", "# # Copyright (c) 2016, Emlid Limited # All rights reserved. # #", "assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count ==", "<NAME> and <NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid Limited # All", "== 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count ==", "self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count", "== 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count", "self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count", "self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count", "def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0", "(INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE", "and use in source and binary forms, # with or without modification, #", "# with or without modification, # are permitted provided that the following conditions", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "THE POSSIBILITY OF SUCH DAMAGE. import pytest import mock from wificontrol import WiFiControl", "OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND", "self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1", "from this software # without specific prior written permission. # # THIS SOFTWARE", "'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert", "INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,", "assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count ==", "import mock from wificontrol import WiFiControl @pytest.fixture def ssid(): network = { 'ssid':", "1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert", "copyright holder nor the names of its contributors # may be used to", "self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started", "BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS", "== 1 def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False", "else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect,", "== 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count ==", "1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert", "ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert state", "args, timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started =", "1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args)", "self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count", "without modification, # are permitted provided that the following conditions are met: #", "# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE", "Written by <NAME> and <NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid Limited", "1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count == 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert", "== self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value =", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "assert state == self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid): def start_connecting(*args):", "mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False)", "may be used to endorse or promote products derived from this software #", "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN", "None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert", "= start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def", "software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "(ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count ==", "this list of conditions and the following disclaimer. # # 2. Redistributions in", "= mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count ==", "1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value", "mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count ==", "class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock()", "self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1", "self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert", "self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def", "above copyright notice, # this list of conditions and the following disclaimer in", "= mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started =", "self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started", "== 1 self.manager.get_ip() assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect()", "== 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid,", "# # 2. Redistributions in binary form must reproduce the above copyright notice,", "<NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid Limited # All rights reserved.", "<filename>tests/test_wificontrol.py # Written by <NAME> and <NAME> <<EMAIL>> # # Copyright (c) 2016,", "self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False", "self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1", "def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count ==", "the following disclaimer in the documentation # and/or other materials provided with the", "BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN", "== 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self):", "== 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started =", "mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count == 1 assert", "{ 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock()", "other materials provided with the distribution. # # 3. Neither the name of", "self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert", "self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started", "OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE", "timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name =", "state == self.manager.WPA_STATE assert status == ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value", "provided with the distribution. # # 3. Neither the name of the copyright", "= mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count ==", "def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1", "= { 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi =", "== 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started =", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF", "= True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert", "1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count ==", "name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count ==", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED", "test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert", "assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name", "TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR", "LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #", "False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count ==", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "= mock.Mock(return_value=True) state, status = self.manager.get_status() assert state == self.manager.HOST_STATE assert status is", "LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A", "== 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count", "1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure,", "= mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert state == self.manager.HOST_STATE", "# 1. Redistributions of source code must retain the above copyright notice, #", "== 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid):", "if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started", "self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count", "self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state,", "self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args =", "THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "to endorse or promote products derived from this software # without specific prior", "# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL", "CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT", "import pytest import mock from wificontrol import WiFiControl @pytest.fixture def ssid(): network =", "== 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert", "network = { 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi", "1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def", "derived from this software # without specific prior written permission. # # THIS", "= 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1", "list of conditions and the following disclaimer. # # 2. Redistributions in binary", "the names of its contributors # may be used to endorse or promote", "Copyright (c) 2016, Emlid Limited # All rights reserved. # # Redistribution and", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "holder nor the names of its contributors # may be used to endorse", "def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def", "== 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name", "must reproduce the above copyright notice, # this list of conditions and the", "self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count", "# All rights reserved. # # Redistribution and use in source and binary", "assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi()", "# this list of conditions and the following disclaimer. # # 2. Redistributions", "OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, #", "THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", "= \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count ==", "be used to endorse or promote products derived from this software # without", "self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1", "1. Redistributions of source code must retain the above copyright notice, # this", "disclaimer in the documentation # and/or other materials provided with the distribution. #", "1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count ==", "return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot", "== 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False", "status == ssid def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started", "args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results()", "= mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count", "self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1", "def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl:", "'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name,", "status = self.manager.get_status() assert state == self.manager.WPA_STATE assert status == ssid def test_start_connection(self,", "assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on()", "False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert", "mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest import mock from wificontrol", "# 2. Redistributions in binary form must reproduce the above copyright notice, #", "self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert", "1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def", "10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count", "# # 3. Neither the name of the copyright holder nor the names", "self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value =", "name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name)", "assert self.manager.wifi.get_device_ip.call_count == 1 self.manager.stop_connecting() assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count ==", "1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1", "mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager =", "FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED", "mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1", "== 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert", "1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,))", "= 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value =", "INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND #", "in the documentation # and/or other materials provided with the distribution. # #", "self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def test_network_add(self,", "== 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert", "== 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count ==", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid)", "'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant =", "the above copyright notice, # this list of conditions and the following disclaimer", "self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1", "test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started =", "assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count ==", "self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1", "start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if args: callback({}, *args) else: callback(result)", "USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "= mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count", "= mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF", "WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. #", "assert self.manager.wpasupplicant.stop_connecting.call_count == 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count ==", "= mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count", "of conditions and the following disclaimer. # # 2. Redistributions in binary form", "self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value =", "products derived from this software # without specific prior written permission. # #", "'11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value =", "must retain the above copyright notice, # this list of conditions and the", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value =", "mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1", "setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count ==", "= mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert", "documentation # and/or other materials provided with the distribution. # # 3. Neither", "AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR", "# without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert", "HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl()", "def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks()", "A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER", "= mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def", "the above copyright notice, # this list of conditions and the following disclaimer.", "the distribution. # # 3. Neither the name of the copyright holder nor", "assert self.manager.hotspot.start.call_count == 0 def test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid):", "conditions and the following disclaimer in the documentation # and/or other materials provided", "test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert", "COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2", "1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started =", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE", "state, status = self.manager.get_status() assert state == self.manager.WPA_STATE assert status == ssid def", "test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name", "self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status =", "assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr", "self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count", "binary forms, # with or without modification, # are permitted provided that the", "TestWiFiControl: def setup_method(self): self.manager = FakeWiFiControl() def test_host_mode(self): self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.start_host_mode() assert", "ssid(): network = { 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self):", "IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING", "SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest", "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT", "1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout):", "1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name =", "1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def", "WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #", "assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False)", "mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count ==", "name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert", "OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE", "mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count == 1 assert", "self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count", "status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state,", "ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self, ssid):", "= mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state == self.manager.WPA_STATE assert status ==", "OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started =", "= name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert", "self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1", "assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert", "self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1", "and the following disclaimer. # # 2. Redistributions in binary form must reproduce", "'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl): def __init__(self): self.wifi = mock.MagicMock() self.wpasupplicant", "# Redistribution and use in source and binary forms, # with or without", "= mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count", "self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert self.manager.wpasupplicant.get_added_networks.call_count", "self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES", "LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert", "mock.Mock(return_value=False) self.manager.start_host_mode() assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count ==", "contributors # may be used to endorse or promote products derived from this", "1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0", "self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count ==", "that the following conditions are met: # # 1. Redistributions of source code", "with the distribution. # # 3. Neither the name of the copyright holder", "INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #", "mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count == 1 assert self.manager.wpasupplicant.get_p2p_name.call_count == 1", "1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert", "code must retain the above copyright notice, # this list of conditions and", "self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args = (ssid, self.manager.revert_on_connect_failure, None, 10)", "self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test'", "self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1", "the following conditions are met: # # 1. Redistributions of source code must", "import WiFiControl @pytest.fixture def ssid(): network = { 'ssid': 'Test' } return network", "OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 1 assert self.manager.wpasupplicant.started.call_count", "self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert", "assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 0 assert self.manager.hotspot.start.call_count == 0 def", "self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count ==", "test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count == 1 self.manager.get_added_networks() assert", "assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert", "== 1 assert self.manager.wpasupplicant.stop.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid):", "status = self.manager.get_status() assert state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value =", "self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode()", "assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid)", "mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert state == self.manager.HOST_STATE assert", "Redistributions in binary form must reproduce the above copyright notice, # this list", "assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert", "def test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect", "OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN", "# 3. Neither the name of the copyright holder nor the names of", "# # Redistribution and use in source and binary forms, # with or", "== 1 self.manager.disconnect() assert self.manager.wpasupplicant.disconnect.call_count == 1 self.manager.get_device_name() assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name()", "def test_verify_names(self): name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value =", "nor the names of its contributors # may be used to endorse or", "True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi() assert self.manager.wifi.block.call_count ==", "= '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value = \"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "by <NAME> and <NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid Limited #", "assert self.manager.hotspot.start.call_count == 1 def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value", "assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self):", "FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT", "self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name)", "the documentation # and/or other materials provided with the distribution. # # 3.", "assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self): self.manager.wpasupplicant.started = mock.Mock(return_value=True) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_off_wifi()", "notice, # this list of conditions and the following disclaimer in the documentation", "mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.started.call_count ==", "assert self.manager.hotspot.get_host_name.call_count == 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name)", "start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid, callback=self.manager.reconnect, args=(ssid,)) assert self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self):", "assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name = 'test' mac_addr =", "name = 'test' mac_addr = '11:22:33:44:55:66' self.manager.hotspot.get_host_name.return_value = name self.manager.wpasupplicant.get_p2p_name.return_value = name self.manager.hotspot.get_hostap_name.return_value", "is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status", "= (ssid, self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count", "mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state == self.manager.WPA_STATE assert status == ssid", "ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting", "test_network_add(self, ssid): self.manager.add_network(ssid) assert self.manager.wpasupplicant.add_network.is_called_once_with(ssid) def test_network_remove(self, ssid): self.manager.remove_network(ssid) assert self.manager.wpasupplicant.remove_network.is_called_once_with(ssid) def test_status_get(self,", "== 1 assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE", "self.manager.hotspot.started.return_value = False if args: callback({}, *args) else: callback(result) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect", "\"{}{}\".format(name, mac_addr[-6:]) self.manager.hotspot.get_device_mac.return_value = mac_addr[-6:] assert self.manager.verify_hostap_name(name) assert self.manager.verify_device_names(name) assert self.manager.hotspot.get_host_name.call_count == 1", "EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY", "1 assert self.manager.hotspot.started.call_count == 1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started =", "1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name) def test_verify_names(self): name", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "reserved. # # Redistribution and use in source and binary forms, # with", "# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY", "SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT", "== 1 self.manager.get_hostap_name() assert self.manager.hotspot.get_hostap_name.call_count == 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count", "1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False)", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest import mock", "self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status() assert state == self.manager.HOST_STATE assert status", "1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count", "endorse or promote products derived from this software # without specific prior written", "def test_status_get(self, ssid): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) state, status = self.manager.get_status()", "are permitted provided that the following conditions are met: # # 1. Redistributions", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", "self.manager.revert_on_connect_failure, None, 10) assert self.manager.wpasupplicant.start_connecting.is_called_once_with(args) assert self.manager.hotspot.started.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1", "SUCH DAMAGE. import pytest import mock from wificontrol import WiFiControl @pytest.fixture def ssid():", "test_start_connection(self, ssid): def start_connecting(*args): self.manager.hotspot.started.return_value = False self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect =", "def test_reconnection(self, ssid): def start_connecting(result, callback, args, timeout): self.manager.hotspot.started.return_value = False if args:", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS;", "@pytest.fixture def ssid(): network = { 'ssid': 'Test' } return network class FakeWiFiControl(WiFiControl):", "== 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started", "is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count", "NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER", "self.manager.get_status() assert state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value", "the following disclaimer. # # 2. Redistributions in binary form must reproduce the", "CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN", "self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self):", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF", "1 assert self.manager.hotspot.start.call_count == 1 def test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count", "assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert", "POSSIBILITY OF SUCH DAMAGE. import pytest import mock from wificontrol import WiFiControl @pytest.fixture", "False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state == self.manager.WPA_STATE assert", "self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count", "2. Redistributions in binary form must reproduce the above copyright notice, # this", "in source and binary forms, # with or without modification, # are permitted", "test_client_mode(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1", "self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.stop.call_count == 1 self.manager.wpasupplicant.started.return_value = False assert self.manager.get_wifi_turned_on() is", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "the name of the copyright holder nor the names of its contributors #", "binary form must reproduce the above copyright notice, # this list of conditions", "False assert self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True)", "# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest import", "self.manager.wpasupplicant.start.call_count == 1 def test_wifi_turn_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=False) self.manager.turn_on_wifi() assert", "following disclaimer in the documentation # and/or other materials provided with the distribution.", "form must reproduce the above copyright notice, # this list of conditions and", "and <NAME> <<EMAIL>> # # Copyright (c) 2016, Emlid Limited # All rights", "modification, # are permitted provided that the following conditions are met: # #", "WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF", "ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS #", "True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state", "== 1 name = 'test' self.manager.set_device_names(name) assert self.manager.wpasupplicant.set_p2p_name.call_count == 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert", "GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.start.call_count == 1 args", "assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name)", "ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING", "== 1 assert self.manager.wpasupplicant.set_p2p_name.is_called_once_with(name) assert self.manager.hotspot.set_hostap_name.call_count == 1 assert self.manager.hotspot.set_hostap_name.is_called_once_with(name) assert self.manager.hotspot.set_host_name.call_count ==", "materials provided with the distribution. # # 3. Neither the name of the", "this software # without specific prior written permission. # # THIS SOFTWARE IS", "mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert self.manager.wifi.unblock.call_count == 0 assert self.manager.wpasupplicant.started.call_count == 1", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS", "self.manager.revert_on_connect_failure(result=None) self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.wpasupplicant.start_connecting.side_effect = start_connecting self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.start_connecting(ssid) assert self.manager.wpasupplicant.started.call_count", "assert self.manager.hotspot.set_host_name.call_count == 1 assert self.manager.hotspot.set_host_name.is_called_once_with(name) assert self.manager.wifi.restart_dns.call_count == 1 self.manager.set_hostap_password(name) assert self.manager.hotspot.set_hostap_password.is_called_once_with(name)", "__init__(self): self.wifi = mock.MagicMock() self.wpasupplicant = mock.MagicMock() self.hotspot = mock.MagicMock() class TestWiFiControl: def", "== self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value = False self.manager.wpasupplicant.get_status", "# and/or other materials provided with the distribution. # # 3. Neither the", "assert state == self.manager.HOST_STATE assert status is None self.manager.wpasupplicant.started.return_value = True self.manager.hotspot.started.return_value =", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY,", "= mock.Mock(return_value=False) self.manager.start_client_mode() assert self.manager.hotspot.stop.call_count == 1 assert self.manager.wpasupplicant.started.call_count == 1 assert self.manager.wpasupplicant.start.call_count", "assert self.manager.wpasupplicant.start.call_count == 1 self.manager.wpasupplicant.started.return_value = True assert self.manager.get_wifi_turned_on() is True def test_wifi_turn_off(self):", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING,", "# Copyright (c) 2016, Emlid Limited # All rights reserved. # # Redistribution", "self.manager.wpasupplicant.start_connecting.call_count == 2 def test_supplicant_functions(self): self.manager.scan() assert self.manager.wpasupplicant.scan.call_count == 1 self.manager.get_scan_results() assert self.manager.wpasupplicant.get_scan_results.call_count", "self.manager.wpasupplicant.get_status = mock.Mock(return_value=ssid) state, status = self.manager.get_status() assert state == self.manager.WPA_STATE assert status", "source code must retain the above copyright notice, # this list of conditions", "of the copyright holder nor the names of its contributors # may be", "OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "above copyright notice, # this list of conditions and the following disclaimer. #", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "self.manager.get_wifi_turned_on() is False def test_wifi_turn_on_if_wifi_is_on(self): self.manager.wpasupplicant.started = mock.Mock(return_value=False) self.manager.hotspot.started = mock.Mock(return_value=True) self.manager.turn_on_wifi() assert", "# may be used to endorse or promote products derived from this software" ]
[ "madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else", "+ \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft)", "attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '',", "result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF pisa_status = pisa.CreatePDF(", "'', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name':", "has been renamed to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store", "import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile", "DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste your", "DocStore() if doc_dig == 'doc' else DigStore time_now = datetime.now().time() time_date = doc_date", "= filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while", "db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File saved successfully!' return", "digfile = DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id", "mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div =", "out \" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif doc_dig", "collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id':", "= b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def", "if file_ext not in allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext in", "'', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type':", "werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import", "filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter", "filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit()", "{'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if", "+ '. ' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return", "docfile.summary[-4:] == \" out\" or \" out \" in docfile.summary: docfile.doc_type = \"out\"", "request from werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from", "docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile =", "pisa.CreatePDF( source_html, # the HTML to convert dest=result_file) # file handle to receive", "digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice", "fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id", "= request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text", "allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data):", "request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 =", "attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id':", "append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore =", "if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread' return docfile def", "collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename", "for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to", "time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id)", "digfile.time_date = time_date # digfile.summary = request.form.get('summary') # return digfile # def mget_file_time_date(file_date,", "' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id", "'%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true')", "get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode", "dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename except Exception as", "doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date", "doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id')", "'', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'),", "= attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice =", "minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time", "filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id = rent_id", "ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore def", "re from bs4 import BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf import", "datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename", "new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists. The new file has been", "# digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date = doc_date +", "docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath =", "collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data =", "thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if", "\"w+b\") # convert HTML to PDF pisa_status = pisa.CreatePDF( source_html, # the HTML", "\"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary'))))", "to convert dest=result_file) # file handle to receive result # close output file", "'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '',", "not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject =", "request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if", "get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent", "results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x in digfile.summary for", "{'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if", "type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict", "def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def", "= request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename =", "mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile = create_docfile() elif doc_dig == 'doc':", "from datetime import datetime, timedelta from xhtml2pdf import pisa from app import db", "attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr':", "'' file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None, \"Invalid file", "= collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data", "if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or", "get_pr_history from app.dao.rent import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id", "if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]}", "convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as", "time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id')", "TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file):", "summary.replace('draft-doc: ', '') summary = ' '.join([item for item in summary.split() if '@'", "if not format: return None return '.' + (format if format != 'jpeg'", "+ \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id,", "def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice", "get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects,", "validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice =", "attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments = [] file_list", "= time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data)", "is_draft) return docfile # def digfile_object_create(dig_id): # # TODO: Refactor # doc_date =", "= attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 =", "i in range(1, 6): name = 'attachment_' + str(i) fdict[name] = request.form.get(name) or", "doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date =", "elif request.form.get('location_folder'): for file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment)", "get_digfile_row(doc_id) if any(x in docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image", "datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: # digfile = DigStore() # time_now", "mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc':", "= os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id)", "attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '',", "has been renamed to ' + filename + '. ' digfile = DigStore()", "int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined =", "in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return", "= collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data", "= docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor", "= request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0],", "'@' not in item]) if summary[-3:] == ' to': summary = summary[0:-3] return", "append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft)", "+ 'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary", "mime_type) def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1:", "\" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif doc_dig ==", "docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = [] fdict", "== rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for", "attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5", "request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type':", "= get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc", "in range(1, 6): name = 'attachment_' + str(i) fdict[name] = request.form.get(name) or ''", "\"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile:", "file result_file.close() # close output file # return False on success and True", "request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict", "= get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc' for digfile", "dig_id = digfile.id db.session.commit() notice = notice + 'File saved successfully!' return dig_id,", "type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name':", "= rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments'", "attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4)", "= time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): #", "'.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename", "= update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor #", "from werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models", "'', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1],", "'' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore)", "# close output file # return False on success and True on errors", "attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop + 1 doc_id = fdict.get('doc_id')", "else: # digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date = doc_date", "doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile = DocStore() if doc_dig", "pisa_status = pisa.CreatePDF( source_html, # the HTML to convert dest=result_file) # file handle", "time_date = datetime.now() summary = 'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text,", "'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type ==", "DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo,", "timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date", "[(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = [] fdict = {'dfountin': 'all'} if", "docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files)", "doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail", "+ digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results,", "doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined =", "get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 =", "append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile,", "elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile =", "'attachment_' + str(i) fdict[name] = request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id):", "file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML", "recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated", "madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return", "key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles:", "attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'),", "summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary = 'draft-doc:", "else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return", "b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return", "== \" in\" or \" in \" in docfile.summary: docfile.doc_type = \"in\" elif", "range(1, 6): name = 'attachment_' + str(i) fdict[name] = request.form.get(name) or '' return", "notice = notice + 'File saved successfully!' return file_id, notice def validate_image(stream): header", "'in' else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = []", "= datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text", "docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary =", "mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc", "= attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 =", "time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id", "= filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id", "close output file # return False on success and True on errors return", "docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename):", "or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach': for i in", "return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data)", "[file for file in file_list if file.filename] if file_list: if request.form.get('location_db'): for file", "file.filename] if file_list: if request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file)", "Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object,", "request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 =", "TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile = DocStore()", "= os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code as", "def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data,", "== 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return", "secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore,", "doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile()", "attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:]", "get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread' return docfile", "docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile", "for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in", "def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or", "+ 'File saved successfully!' return dig_id, notice # else: # flash('No filename!') #", "os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code as rent", "docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div", "while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new", "with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id)", "datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def", "+ str(loop))) loop = loop + 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft)", "+ file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles,", "= create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if file.filename: attachment", "== 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id,", "if request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if", "else: # flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date =", "docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''):", "'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id ==", "'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict =", "= {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str)", "if filename != '': notice = '' file_ext = os.path.splitext(filename)[1] if file_ext not", "filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file has", "r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if", "for i in range(1, 6): name = 'attachment_' + str(i) fdict[name] = request.form.get(name)", "= old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary =", "summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id,", "app.dao.rent import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id')", "'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4", "notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser')", "'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename)", "'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup)", "rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id,", "db.session.commit() notice = notice + 'File saved successfully!' return dig_id, notice # else:", "def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id ==", "= doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary =", "dig_id, notice # else: # flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id,", "docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\" or \" out \" in", "file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach'", "open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF pisa_status = pisa.CreatePDF( source_html, #", "0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files", "= create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in attachment_details: if attachment.get('attach_id') >", "datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename", "new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary", "return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\")", "return docfile # def digfile_object_create(dig_id): # # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'),", "type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'),", "rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter,", "elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext =", "= {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"}", "secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename =", "[] file_store_filter = [] fdict = {'dfountin': 'all'} if request.method == \"POST\": fdict", "' digfile = DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read()", "digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig = 'file' files = docfiles", "\" out \" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif", "attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 =", "file in file_list if file.filename] if file_list: if request.form.get('location_db'): for file in file_list:", "results = sorted(files, key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for", "or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action ==", "for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in", "\" in \" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\"", "file.time_date.time() if file else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)", "in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined = True return docfile def", "' + new_filename + '. ' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore,", "id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div + ' ' +", "docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile", "\"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach': for i in range(1,", "# doc_time = digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) #", "return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '',", "docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile =", "+ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date", "attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name)", "'.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while", "def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text", "new_filename) try: os.rename(src, dst) filestore.summary = new_filename except Exception as ex: flash(f'Cannot rename", "= get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type)", "def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile,", "return dig_id, notice # else: # flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id,", "flash, request from werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix", "if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image =", "file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list: if file.filename:", "def digfile_object_create(dig_id): # # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if", "'.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\")", "request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject':", "doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new", "request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return", "= fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail =", "'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name,", "DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email", "'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3", "pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files = docfiles", "= 'pr' files = docfiles + pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True)", "= object_type_id docfile.doc_text = 'Write or paste your document here...' docfile.object_id = object_id", "2 pay_request.doc_dig = 'pr' files = docfiles + pay_requests return sorted(files, key=lambda r:", "time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): # #", "{'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id,", "file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig", "old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename:", "attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2", "'. ' digfile = DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data =", "{str(ex)}', 'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ',", "recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients, subject, attachments def", "# upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor", "= collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list = [file for file", "writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF", "email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '',", "= \"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined = True return", "'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments", "get_digfile_object(doc_object_id) if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image", "return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def", "= os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename except Exception as ex:", "file_store_files: file.doc_dig = 'file' files = docfiles + digfiles + file_store_files results =", "file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary)", "HTML to convert dest=result_file) # file handle to receive result # close output", "errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary", "'', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type':", "file_store_filter = [] fdict = {'dfountin': 'all'} if request.method == \"POST\": fdict =", "= '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore =", "attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 =", "file. Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary =", "get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object,", "is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def", "file # return False on success and True on errors return pisa_status.err def", "import re from bs4 import BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf", "'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0,", "return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig)", "' + summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False):", "# time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id,", "timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data()", "mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file else datetime.now().time() # time_date =", "fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles,", "= filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush()", "attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig", "time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower()", "b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext", "combined = True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text':", "digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id =", "attachment_div = attachment_div + ' ' + attachment.file_name attachment_div = attachment_div + \"</div><br>\"", "\\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data =", "object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests:", "docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread'", "def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div", "function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date", "+ '. ' digfile = DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data", "upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile =", "= b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id)", "return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id =", "= datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second)", "successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup", "else DigStore time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else:", "pisa from app import db from flask import current_app, flash, request from werkzeug.utils", "= update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id)", "> 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop + 1", "= {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)}", "as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore", "= html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "file_store = FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store)", "import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore, FileStore,", "= append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore", "type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id',", "already exists. The new file has been renamed to ' + filename +", "mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date", "return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x in digfile.summary", "uploaded_file): # TODO: Refactor # new digital file uses upload function # rentcode", "= {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)}", "datetime, timedelta from xhtml2pdf import pisa from app import db from flask import", "return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text,", "if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list: if", "type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name',", "mupdate_filename_suffix(filename) notice = 'File already exists. The new file has been renamed to", "= datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile = DocStore() if doc_dig ==", "{'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details", "# flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'),", "if doc_dig == 'doc' else DigStore time_now = datetime.now().time() time_date = doc_date +", "0: docfile = create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig", "successfully!' return dig_id, notice # else: # flash('No filename!') # return redirect(request.url) def", "digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary", "os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with", "attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 =", "\"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists.", "= request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0],", "digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary = request.form.get('summary') # return", "file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id,", "import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile,", "output file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert", "rent_id, summary): time_date = datetime.now() summary = 'draft-doc: ' + summary docfile =", "app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row,", "= 'File already exists. The new file has been renamed to ' +", "def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] ==", "append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second)", "notice def validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not", "file in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for", "object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file", "from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile,", "'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5", "doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods',", "\\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return", "seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time =", "FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id", "<reponame>hezmondo/lulu import imghdr import os import re from bs4 import BeautifulSoup from datetime", "type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id',", "digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice", "x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary:", "dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile,", "str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n',", "'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter out", "= get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1", "= mupdate_filename_suffix(filename) notice = 'File already exists. The new file has been renamed", "digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files", "create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if file.filename: attachment =", "datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def", "else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO:", "return attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if", "'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div =", "docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] # #", "os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1 =", "def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def", "saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary)", "file_id = file_store.id db.session.commit() notice = notice + 'File saved successfully!' return file_id,", "notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data)", "'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$')", "'', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name':", "append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename =", "= [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = [] fdict = {'dfountin': 'all'}", "return digfile def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary", "'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach': for", "= os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None, \"Invalid file suffix\" elif", "import os import re from bs4 import BeautifulSoup from datetime import datetime, timedelta", "\"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary for", "already exists. The new file has been renamed to ' + new_filename +", "docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data()", "Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(),", "import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile,", "Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename return", "return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile = digfile_object_create(dig_id)", "request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date,", "rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for x in", "attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id':", "1 for attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_'", "secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row", "dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf')", "' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date =", "update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile)", "time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return", "request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type':", "'.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\")", "else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] #", "= {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str)", "elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext =", "'File saved successfully!' return dig_id, notice # else: # flash('No filename!') # return", "from flask import current_app, flash, request from werkzeug.utils import secure_filename from app.main.common import", "docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\"", "= 'dig' for file in file_store_files: file.doc_dig = 'file' files = docfiles +", "= docfiles + digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True)", "= soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject),", "if any(x in docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image =", "if doc_id == 0: docfile = create_docfile() elif doc_dig == 'doc': docfile =", "' to': summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id)", "dst) filestore.summary = new_filename except Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}',", "docfile.summary = 'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for", "request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'):", "= 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter", "as rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for x", "return docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter out draft", "b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id)", "True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread'", "= notice + 'File saved successfully!' return dig_id, notice # else: # flash('No", "def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile = create_docfile() elif doc_dig ==", "def mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter out draft docs #", "docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span')", "docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def", "file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id):", "= docfiles + pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig):", "= datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date", "renamed to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore()", "digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results def", "elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return", "dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new", "notice + 'File saved successfully!' return file_id, notice def validate_image(stream): header = stream.read(512)", "is_draft=False): attachment_details, fdict = collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list =", "attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5", "docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc: ' +", "docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def", "docfile = DocStore() if doc_dig == 'doc' else DigStore time_now = datetime.now().time() time_date", "== 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type", "to ' + new_filename + '. ' if notice: flash(notice, 'message') filestore =", "current_app, flash, request from werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir,", "docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type,", "= 1 for attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'),", "DigStore time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile", "= get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \" in \" in docfile.summary:", "file has been renamed to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename))", "# digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id,", "receive result # close output file result_file.close() # close output file # return", "db.session.flush() file_id = file_store.id db.session.commit() notice = notice + 'File saved successfully!' return", "filestore.summary = new_filename except Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error')", "return None, \"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif']", "'File already exists. The new file has been renamed to ' + new_filename", "get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row,", "return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital file", "subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return", "return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if", "notice = 'File already exists. The new file has been renamed to '", "= file_store.id db.session.commit() notice = notice + 'File saved successfully!' return file_id, notice", "files = docfiles + pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id,", "as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else:", "if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id ==", "filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id':", "docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return", "digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles,", "pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id ==", "= object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice =", "{'dfountin': 'all'} if request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode'))))", "+ new_filename + '. ' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename,", "= os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename", "in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\" or \" out", "docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id > 0:", "0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id':", "new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists.", "file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO:", "def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) #", "action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id)", "output_filename), \"w+b\") # convert HTML to PDF pisa_status = pisa.CreatePDF( source_html, # the", "if '@' not in item]) if summary[-3:] == ' to': summary = summary[0:-3]", "mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files =", "timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time()", "= os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1", "Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile = DocStore() if", "= request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(),", "return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time()", "= [file for file in file_list if file.filename] if file_list: if request.form.get('location_db'): for", "attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath,", "or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id)", "= filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename,", "to ' + filename + '. ' digfile = DigStore() digfile.time_date = time_date", "= object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File", "attachment_div + ' ' + attachment.file_name attachment_div = attachment_div + \"</div><br>\" html =", "docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\"", "collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list = [file for file in", "file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles +", "with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file):", "return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary = ' '.join([item", "seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'),", "file else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return", "DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id", "in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif", "# if dig_id == 0: # digfile = DigStore() # time_now = datetime.now().time()", "'thread' docfile.summary = 'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id)", "# TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id,", "for item in summary.split() if '@' not in item]) if summary[-3:] == '", "doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date =", "= request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary =", "\" out\" or \" out \" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type", "attachment in attachments: attachment_div = attachment_div + ' ' + attachment.file_name attachment_div =", "return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date", "pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89]", "doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id", "suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream):", "== 'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id) else:", "get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = '' filestore =", "os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename except", "upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now =", "docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output file for writing", "doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\"", "'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '',", "'.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date =", "attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 =", "= [] file_store_filter = [] fdict = {'dfountin': 'all'} if request.method == \"POST\":", "datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile = DocStore() if doc_dig == 'doc'", "= create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients =", "'%Y-%m-%d') # if dig_id == 0: # digfile = DigStore() # time_now =", "= [] file_list = fdict.get('file_list') file_list = [file for file in file_list if", "DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date", "uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id =", "time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id", "mpost_digfile_object(dig_id): # # TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # #", "'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict", "timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice = ''", "{'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if", "filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id)", "get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64 import", "doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute,", "# TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id,", "# return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now =", "while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The", "= {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)}", "attachment.file_name attachment_div = attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text =", "request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details =", "= fdict.get('subject') return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open", "attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id':", "Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): #", "else: for file in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop =", "summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft)", "b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile", "b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def", "docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO:", "return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time", "file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename =", "Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str)", "minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename =", "time_date # digfile.summary = request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None): #", "return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if", "file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice = notice +", "digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id", "else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date", "has been renamed to ' + filename + '. ' digfile = DigFile()", "get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64", "get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import", "attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1',", "docfile = get_digfile_row(doc_id) if any(x in docfile.summary for x in ['.png', '.jpg', '.jpeg',", "dest=result_file) # file handle to receive result # close output file result_file.close() #", "if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]}", "Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc:", "docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread' return docfile def mget_docfiles_combo(rent_id):", "digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf'", "result_file.close() # close output file # return False on success and True on", "'', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1],", "request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date =", "# digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary = request.form.get('summary') #", "attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '',", "= True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text,", "= BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text", "= secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file)", "saved successfully!' return file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0) format =", "type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type',", "def mget_digfile_object(doc_object_id): # TODO: refactor same code as rent digfile getter digfile =", "docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x in", "in summary.split() if '@' not in item]) if summary[-3:] == ' to': summary", "'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def", "for docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out", "= file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): #", "DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\", "seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile =", "filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments:", "'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in", "prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject =", "' digfile = DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read()", "= int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined", "'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date", "attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id':", "attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4", "from xhtml2pdf import pisa from app import db from flask import current_app, flash,", "'', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name':", "file_store.id db.session.commit() notice = notice + 'File saved successfully!' return file_id, notice def", "in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list:", "def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file else datetime.now().time() # time_date", "'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '',", "new_filename + '. ' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename)", "pay_request.doc_dig = 'pr' files = docfiles + pay_requests return sorted(files, key=lambda r: r.time_date,", "DigStore() # time_now = datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second)", "mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital file uses upload function #", "0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id':", "= request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0],", "dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row,", "collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data =", "pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files = docfiles + pay_requests return", "False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def", "= DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id =", "= doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id =", "= pisa.CreatePDF( source_html, # the HTML to convert dest=result_file) # file handle to", "object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice", "attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5:", "digfile.id db.session.commit() notice = notice + 'File saved successfully!' return dig_id, notice def", "= append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile", "'' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id", "docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action ==", "time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig", "'. ' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore", "notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile):", "== \" out\" or \" out \" in docfile.summary: docfile.doc_type = \"out\" else:", "get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def", "to ' + filename + '. ' digfile = DigFile() digfile.time_date = time_date", "is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile,", "get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc =", "doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary')", "minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile", "validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format: return", "= get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = '' filestore", "digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id):", "doc_id == 0: docfile = create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id)", "get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary =", "summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\",", "# digfile = DigStore() # time_now = datetime.now().time() # time_date = doc_date +", "' + attachment.file_name attachment_div = attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text", "x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary:", "rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src,", "+ \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data", "= request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0],", "def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined", "docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date =", "DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta,", "= digfile.id db.session.commit() notice = notice + 'File saved successfully!' return dig_id, notice", "'pr' files = docfiles + pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def", "TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id", "# # TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return", "HTML to PDF pisa_status = pisa.CreatePDF( source_html, # the HTML to convert dest=result_file)", "flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "{'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if", "= [] fdict = {'dfountin': 'all'} if request.method == \"POST\": fdict = mget_fdict(action)", "= pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files = docfiles + pay_requests", "None, \"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and", "old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists. The new", "and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename =", "attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile =", "fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary'))))", "{'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4", "r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles =", "= notice + 'File saved successfully!' return file_id, notice def validate_image(stream): header =", "renamed to ' + filename + '. ' digfile = DigStore() digfile.time_date =", "= [] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1", "= datetime.now() summary = 'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text, rent_id,", "time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id", "reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x in", "key=lambda r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles", "summary = 'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return", "= request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date +", "file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath,", "attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3", "in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf", "docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf'", "post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile =", "+ 'File saved successfully!' return file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0)", "summary[-3:] == ' to': summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile", "'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf',", "'.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile", "docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile = digfile_object_create(dig_id) #", "'. ' digfile = DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data =", "= post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile", "def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date", "'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig ==", "summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile =", "return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary", "doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: # digfile = DigStore()", "= digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id =", "attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '',", "summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data =", "open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block,", "new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename", "file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext !=", "import BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf import pisa from app", "docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital file uses", "attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id',", "' '.join([item for item in summary.split() if '@' not in item]) if summary[-3:]", "append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File", "get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files results", "or paste your document here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id):", "except Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename", "'%Y-%m-%d') if doc_id == 0: docfile = DocStore() if doc_dig == 'doc' else", "attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '',", "def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject", "doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject')", "Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file =", "create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list: if file.filename: attachment = create_attachment_as_temp(file)", "create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice", "doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data,", "= mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files results = sorted(files, key=lambda", "# TODO: Refactor # new digital file uses upload function # rentcode =", "convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(),", "digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in", "= mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if", "= email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore,", "doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def append_digfile_form_data(digfile):", "collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list", "filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file has been", "== 'doc' else DigStore time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute,", "# # filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter =", "attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list: if file.filename: attachment", "'.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\", "FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles,", "= DigStore() # time_now = datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute,", "convert dest=result_file) # file handle to receive result # close output file result_file.close()", "def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary = 'draft-doc: ' + summary", "email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename,", "int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined", "str(i) fdict[name] = request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile =", "request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str),", "open output file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") #", "DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id", "= DocStore() if doc_dig == 'doc' else DigStore time_now = datetime.now().time() time_date =", "summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now =", "def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id,", "'%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data():", "True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary':", "= b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files:", "[request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'),", "request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str),", "= request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename,", "doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary':", "type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type',", "def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital file uses upload function", "doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice", "notice + 'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now()", "digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id')", "= secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename", "file_store.time_date = time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id =", "if docfile.summary[-3:] == \" in\" or \" in \" in docfile.summary: docfile.doc_type =", "if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]}", "docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id =", "for file in file_store_files: file.doc_dig = 'file' files = docfiles + digfiles +", "digfiles: digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig = 'file' files =", "'.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date", "# def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile)", "== ' to': summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile =", "object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary':", "get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles", "docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id", "= \"in\" docfile.doc_text = \"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile", "= secure_filename(uploaded_file.filename).lower() if filename != '': notice = '' file_ext = os.path.splitext(filename)[1] if", "loop = 1 for attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'),", "file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files results = sorted(files,", "has been renamed to ' + new_filename + '. ' if notice: flash(notice,", "digital file uses upload function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text =", "Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name',", "attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop +", "fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename):", "seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice = '' file_ext =", "filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary = ' '.join([item for", "return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in", "doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles:", "in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out'", "source_html, # the HTML to convert dest=result_file) # file handle to receive result", "handle to receive result # close output file result_file.close() # close output file", "== 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute,", "minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date =", "'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile", "def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return", "update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice =", "digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code as rent digfile getter", "os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename except Exception as ex: flash(f'Cannot", "= int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date':", "for attachment in attachments: attachment_div = attachment_div + ' ' + attachment.file_name attachment_div", "'File already exists. The new file has been renamed to ' + filename", "'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str),", "doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date =", "= rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File", "docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile()", "get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history", "fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif", "= sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles =", "file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id,", "if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date +", "+ '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary =", "elif doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return", "[] file_list = fdict.get('file_list') file_list = [file for file in file_list if file.filename]", "app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64 import b64encode def", "uses upload function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now =", "None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already", "is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile", "dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False):", "html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now", "exists. The new file has been renamed to ' + new_filename + '.", "'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0,", "in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop", "object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date +", "file_store_files): for digfile in digfiles: if any(x in digfile.summary for x in ['.png',", "return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename),", "docfile.summary[-3:] == \" in\" or \" in \" in docfile.summary: docfile.doc_type = \"in\"", "# TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile =", "'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile", "0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id':", "mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text,", "old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary = new_filename except Exception", "new file has been renamed to ' + filename + '. ' digfile", "= get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def", "os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0,", "type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name',", "file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files):", "if doc_id == 0: docfile = DocStore() if doc_dig == 'doc' else DigStore", "return digfile # def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file else", "update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89]", "+ ' ' + attachment.file_name attachment_div = attachment_div + \"</div><br>\" html = attachment_div", "same code as rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary", "['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time =", "attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file)", "get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb')", "doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def", "# new digital file uses upload function # rentcode = request.form.get(\"rentcode\") doc_date =", "= fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html,", "update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail,", "mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\",", "dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file", "return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File", "notice # else: # flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file):", "filepath, mime_type) def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str) if", "docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out' return", "in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id,", "create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id,", "file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form():", "= create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list: if file.filename: attachment =", "!= validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice", "timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename", "digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def", "= int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89]", "'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$')", "request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'):", "rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file has", "digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict", "docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or", "return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return", "rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary):", "= doc_form_data.get('summary') if not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text =", "Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent", "= 'file' files = docfiles + digfiles + file_store_files results = sorted(files, key=lambda", "= b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id,", "= stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format: return None return", "'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath", "filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row =", "appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output file for", "'.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id):", "docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\",", "here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for", "= time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id", "+ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else", "' ' + attachment.file_name attachment_div = attachment_div + \"</div><br>\" html = attachment_div +", "doc_dig == 'doc' else DigStore time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour,", "item]) if summary[-3:] == ' to': summary = summary[0:-3] return summary def update_docfile(doc_id,", "0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1,", "fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or", "bs4 import BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf import pisa from", "request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 =", "timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date", "request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour,", "old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary = '", "'-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already exists.", "document here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id)", "subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated binary)", "create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients')", "is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile", "attachments.append(attachment) else: for file in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop", "= get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig", "return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if", "attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc =", "'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second)", "\"in\" docfile.doc_text = \"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile =", "or \" in \" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \"", "TODO: refactor same code as rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x", "from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64 import b64encode", "docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste your document", "docfiles def mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter out draft docs", "madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id", "filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type)", "combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary = 'draft-doc: ' +", "= datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) +", "= mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath,", "request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach': for i", "attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2", "reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile = create_docfile() elif doc_dig", "digfile # def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file else datetime.now().time()", "= str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return email_to,", "minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date =", "= 'attachment_' + str(i) fdict[name] = request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id,", "datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to =", "def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in docfile.summary.split():", "been renamed to ' + new_filename + '. ' if notice: flash(notice, 'message')", "your document here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests =", "'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary = 'draft-doc: '", "format: return None return '.' + (format if format != 'jpeg' else 'jpg')", "['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf =", "'attach': for i in range(1, 6): name = 'attachment_' + str(i) fdict[name] =", "flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary):", "not in item]) if summary[-3:] == ' to': summary = summary[0:-3] return summary", "= get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files", "docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor #", "!= '': notice = '' file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes():", "docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data()", "seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def", "attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1)", "pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files = docfiles +", "in \" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\" or", "def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text':", "doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id')", "# else: # flash('No filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date", "= '' file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None, \"Invalid", "= datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True", "+ str(i) fdict[name] = request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile", "= filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice =", "= \"out\" else: docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id)", "mget_docfiles(rent_id, action=''): digfile_filter = [] # # filter out draft docs # docfile_filter", "attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$')", "'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id)", "summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id", "attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4:", "attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id)", "digfile = DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id", "mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary,", "renamed to ' + filename + '. ' digfile = DigFile() digfile.time_date =", "action=''): digfile_filter = [] # # filter out draft docs # docfile_filter =", "= object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in", "sorted(files, key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in", "summary = summary.replace('draft-doc: ', '') summary = ' '.join([item for item in summary.split()", "+ pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id", "name = 'attachment_' + str(i) fdict[name] = request.form.get(name) or '' return fdict def", "in\" or \" in \" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] ==", "post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from", "attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '',", "request.form.get(\"doc_text\") or \"\"} if action == 'attach': for i in range(1, 6): name", "else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile =", "'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def", "request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id'))", "rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles,", "for file in file_list if file.filename] if file_list: if request.form.get('location_db'): for file in", "= request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None): # time = file.time_date.time()", "in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id,", "== \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary'))))", "docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = [] fdict = {'dfountin':", "'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice", "filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type ==", "datetime import datetime, timedelta from xhtml2pdf import pisa from app import db from", "Refactor # digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def", "success and True on errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date", "\"\"} if action == 'attach': for i in range(1, 6): name = 'attachment_'", "for attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' +", "return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath =", "'.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename,", "return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\"", "'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name,", "to PDF pisa_status = pisa.CreatePDF( source_html, # the HTML to convert dest=result_file) #", "fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail']", "attachment_div = attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text = html", "type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name':", "rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary =", "type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id',", "os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date =", "datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text =", "= append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile)", "src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst) filestore.summary =", "r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile = create_docfile()", "import datetime, timedelta from xhtml2pdf import pisa from app import db from flask", "= \"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if", "+ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) # doc_time =", "= doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile,", "True on errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'),", "from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary')", "refactor same code as rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x in", "append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile =", "create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary = 'draft-doc: ' + summary docfile", "\" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\" or \"", "def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def", "attachments = [] file_list = fdict.get('file_list') file_list = [file for file in file_list", "digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id)", "def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict", "dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file:", "else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments =", "attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3", "mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id)", "'.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour,", "'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0,", "docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:] == \" out\" or \" out \"", "digfile getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for x in ['.png',", "0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop + 1 doc_id", "notice + 'File saved successfully!' return dig_id, notice # else: # flash('No filename!')", "docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile =", "file=None): # time = file.time_date.time() if file else datetime.now().time() # time_date = file_date", "+ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice =", "'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$')", "minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() #", "digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data()", "type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name',", "output file result_file.close() # close output file # return False on success and", "attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div +", "time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename !=", "mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date", "import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text,", "stream.seek(0) format = imghdr.what(None, header) if not format: return None return '.' +", "key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile =", "in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in", "docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients", "import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary", "= datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste your document here...'", "rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\"", "time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile", "+ 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id,", "notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary,", "os import re from bs4 import BeautifulSoup from datetime import datetime, timedelta from", "['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\"", "open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id,", "= True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig =", "datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-'", "False on success and True on errors return pisa_status.err def collect_dig_form_data(): rent_id =", "+ timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor", "\\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import", "{'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2", "# def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file else datetime.now().time() #", "= new_filename except Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary", "attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data) elif", "{'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3", "file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in", "app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists,", "docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig = 'dig' for file in", "= get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread' return", "upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile", "fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id)", "> 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles,", "== 'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary for x in ['.png',", "the HTML to convert dest=result_file) # file handle to receive result # close", "= 2 pay_request.doc_dig = 'pr' files = docfiles + pay_requests return sorted(files, key=lambda", "file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file", "sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile", "uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice", "mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files results = sorted(files, key=lambda r:", "filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary", "uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date =", "request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return", "filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary", "datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile", "docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0:", "request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text =", "= {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id):", "time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date =", "= datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: #", "else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return", "The new file has been renamed to ' + new_filename + '. '", "update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id):", "time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile =", "attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with", "object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file has", "', '') summary = ' '.join([item for item in summary.split() if '@' not", "collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary", "= get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files", "convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form():", "file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int),", "= time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id =", "= current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients, subject,", "= doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return docfile def", "file_ext not in allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext in ['.bmp',", "\"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div + ' '", "return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary =", "seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date", "doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc'", "attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5',", "if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments,", "docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id) if docfile: docfile.doc_dig", "'.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return", "= update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): #", "get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile", "= notice + 'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date =", "elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary for x", "'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary =", "else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined': combined}", "['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf =", "request.form.get('attachment_5', '', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type':", "doc_dig): if doc_id == 0: docfile = create_docfile() elif doc_dig == 'doc': docfile", "doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id')", "attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4',", "= summary.replace('draft-doc: ', '') summary = ' '.join([item for item in summary.split() if", "on errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return", "file handle to receive result # close output file result_file.close() # close output", "if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]}", "= request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\")", "not in allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg',", "mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \"", "else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time()", "file_list = [file for file in file_list if file.filename] if file_list: if request.form.get('location_db'):", "append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore", "rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc =", "digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO:", "if new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already", "def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile,", "return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile,", "'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$')", "def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename =", "dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile,", "mget_digfile_object(doc_object_id): # TODO: refactor same code as rent digfile getter digfile = get_digfile_object(doc_object_id)", "= \"in\" elif docfile.summary[-4:] == \" out\" or \" out \" in docfile.summary:", "= request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date", "return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def", "def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return", "'File saved successfully!' return file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0) format", "in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files =", "' + filename + '. ' digfile = DigFile() digfile.time_date = time_date digfile.summary", "for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr'", "filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file:", "any(x in docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\")", "app import db from flask import current_app, flash, request from werkzeug.utils import secure_filename", "doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id =", "madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): # # TODO: Refactor #", "+ '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already", "if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in attachment_details:", "docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename)", "= docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id", "if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]}", "in docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif", "'. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date file_store.summary = filename", "append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(),", "doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else", "mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x in digfile.summary for x in", "if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig':", "= os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date", "The new file has been renamed to ' + filename + '. '", "# return False on success and True on errors return pisa_status.err def collect_dig_form_data():", "mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc", "fdict.get('file_list') file_list = [file for file in file_list if file.filename] if file_list: if", "get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\")", "filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or", "digfile in digfiles: digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig = 'file'", "allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png',", "elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath = os.path.join(mget_filestore_dir(),", "validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice", "mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\")", "+ file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict def", "int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date,", "doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False):", "time = file.time_date.time() if file else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour,", "= doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg',", "= os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id',", "db.session.commit() notice = notice + 'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile):", "'', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name':", "object_type_id docfile.doc_text = 'Write or paste your document here...' docfile.object_id = object_id return", "filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile,", "= docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date", "= fdict.get('file_list') file_list = [file for file in file_list if file.filename] if file_list:", "getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for x in ['.png', '.jpg',", "docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id) else: docfile =", "file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath =", "mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf')", "flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div", "attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3',", "new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment", "request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')}", "in digfiles: if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']):", "return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0:", "# time_now = datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) #", "out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter =", "'dig' for file in file_store_files: file.doc_dig = 'file' files = docfiles + digfiles", "'attachment_' + str(loop))) loop = loop + 1 doc_id = fdict.get('doc_id') docfile =", "import db from flask import current_app, flash, request from werkzeug.utils import secure_filename from", "action == 'attach': for i in range(1, 6): name = 'attachment_' + str(i)", "doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png',", "# return digfile # def mget_file_time_date(file_date, file=None): # time = file.time_date.time() if file", "str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src =", "attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3)", "and True on errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id')) doc_date =", "filename!') # return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now", "= create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig':", "\"&pound;\") docfile.summary = request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath", "filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice", "= os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif", "def mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1", "try: os.rename(src, dst) filestore.summary = new_filename except Exception as ex: flash(f'Cannot rename file.", "= request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False", "minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile #", "in docfiles: docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig = 'dig' for", "def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files", "filename != '': notice = '' file_ext = os.path.splitext(filename)[1] if file_ext not in", "= get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id)", "in allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg',", "docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in", "if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return docfile", "from app import db from flask import current_app, flash, request from werkzeug.utils import", "= append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower()", "not format: return None return '.' + (format if format != 'jpeg' else", "minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig", "return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files =", "file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc' for", "file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in", "doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75]", "fdict = {'dfountin': 'all'} if request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'):", "[] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 =", "attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in attachment_details: if attachment.get('attach_id')", "= collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\", "attachments: attachment_div = attachment_div + ' ' + attachment.file_name attachment_div = attachment_div +", "attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def", "attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2',", "output_filename): # open output file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename),", "DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row,", "in item]) if summary[-3:] == ' to': summary = summary[0:-3] return summary def", "filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div", "request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary = request.form.get('summary')", "\\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\", "= 'in' else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter =", "attachment_3[2]} attachments.append(attachment_3) attachment_4 = request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4", "doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile = update_digfile(doc_id)", "doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): # # TODO: Refactor # doc_date", "file_list = fdict.get('file_list') file_list = [file for file in file_list if file.filename] if", "= {'dfountin': 'all'} if request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode'))))", "notice = notice + 'File saved successfully!' return dig_id, notice # else: #", "= request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date':", "digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile)", "file has been renamed to ' + new_filename + '. ' if notice:", "db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice = notice + 'File saved successfully!'", "r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x", "[] # # filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter", "format = imghdr.what(None, header) if not format: return None return '.' + (format", "+ filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date = time_date", "filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if", "sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id)", "and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename", "'' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour,", "== 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id", "== rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter,", "import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists,", "digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id >", "email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename)", "get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File", "== \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \" in", "request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details,", "doc_form_data.get('summary') if not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text')", "for file in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1", "# TODO: refactor same code as rent digfile getter digfile = get_digfile_object(doc_object_id) if", "== rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles:", "from app.dao.rent import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id =", "doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) # doc_time", "docfile.doc_text = 'Write or paste your document here...' docfile.object_id = object_id return docfile", "reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to =", "from app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import dig_filename_already_exists,", "# def digfile_object_create(dig_id): # # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') #", "upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital", "digfile def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename", "file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id", "request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary = request.form.get('summary') # return digfile #", "= attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 =", "file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code", "= ' '.join([item for item in summary.split() if '@' not in item]) if", "request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type':", "\\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest", "= DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second)", "get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent,", "notice = '' file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None,", "create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(),", "r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if doc_id == 0: docfile = create_docfile() elif", "request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '', type=str)} attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int),", "0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type =", "or \" out \" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\"", "= get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath,", "to': summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile", "files = docfiles + digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date,", "email_to = email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def", "docfile.in_out = 'in' else: docfile.in_out = 'out' return docfiles def mget_docfiles(rent_id, action=''): digfile_filter", "# # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile =", "attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 =", "'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary for x in ['.png', '.jpg',", "for digfile in digfiles: if any(x in digfile.summary for x in ['.png', '.jpg',", "or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now()", "madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data,", "# filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = []", "filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists. The new file has", "filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename)", "attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig, doc_id): if doc_dig == \"doc\":", "docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig =", "= b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id):", "get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig =", "'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach': for i in range(1, 6):", "rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now", "renamed to ' + new_filename + '. ' if notice: flash(notice, 'message') filestore", "= append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = '' filestore = get_file_store_row(doc_id) old_filename", "= str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src", "timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if", "doc_id == 0: docfile = DocStore() if doc_dig == 'doc' else DigStore time_now", "digfile.summary = request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None): # time =", "results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id)", "'%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename =", "docfile.doc_text = \"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id): docfile = get_docfile_combo_meta(rent_id)", "if request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'):", "datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True if", "'.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile", "return madd_digfile_properties(digfile, dig_form_data) def append_docfile_form_data(docfile, is_draft=False): doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data)", "return email_to, re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(),", "# doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: # digfile =", "attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id':", "= doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc: ' + request.form.get(", "filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id,", "digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files =", "soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string", "request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename)", "= b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id):", "docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out =", "'.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') +", "stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format: return None return '.'", "def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id =", "upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent", "= get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute,", "== 0: # digfile = DigStore() # time_now = datetime.now().time() # time_date =", "for file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for", "request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list':", "new file has been renamed to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(),", "b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext", "request.form.get('summary') return docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename)", "= get_digfile_object(doc_object_id) if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']):", "return file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None, header)", "reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary = ' '.join([item for item in", "import pisa from app import db from flask import current_app, flash, request from", "else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id", "BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf import pisa from app import", "'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict =", "request.form.get('xinput').replace(\"£\", \"&pound;\") summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False return", "datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile", "rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig", "def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id,", "draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = []", "doc_form_data = collect_doc_form_data() docfile = append_file_form_time_data(docfile, doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore):", "pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files = docfiles + pay_requests return sorted(files,", "rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'),", "'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2", "docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text", "type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type',", "= DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary =", "filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename =", "file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return", "get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \" in \" in docfile.summary: docfile.doc_type", "time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' +", "docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id):", "filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(),", "doc_time = digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id", "code as rent digfile getter digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for", "digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc' for digfile in digfiles:", "filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename):", "digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice +", "in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor", "filename + '. ' digfile = DigStore() digfile.time_date = time_date digfile.summary = filename", "= \"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary", "= [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'),", "image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists.", "'.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1]", "def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date =", "doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now() summary", "request.form.get('location_folder'): for file in file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else:", "return redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time()", "attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments def mget_docfile(doc_dig,", "os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type", "doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x in docfile.summary for x in", "get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile, upload_docfile, \\ get_digfiles_for_rent, get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from", "def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try:", "= 'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile", "request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary", "'doc' for digfile in digfiles: digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig", "docfile # def digfile_object_create(dig_id): # # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "doc_form_data = collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') +", "not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined =", "attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 =", "type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2,", "return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup =", "os.rename(src, dst) filestore.summary = new_filename except Exception as ex: flash(f'Cannot rename file. Error:", "summary.split() if '@' not in item]) if summary[-3:] == ' to': summary =", "return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date", "= 'Write or paste your document here...' docfile.object_id = object_id return docfile def", "file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename)", "'.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id):", "== 0: docfile = create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif", "== 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig =", "request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str),", "(truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF pisa_status", "filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments = []", "datetime.now() summary = 'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text, rent_id, summary)", "digfile = digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig):", "\"&pound;\") summary = request.form.get('summary')[0:89] combined = True if request.form.get('doc_combo_true') else False return {'rent_id':", "[] fdict = {'dfountin': 'all'} if request.method == \"POST\": fdict = mget_fdict(action) if", "digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc'", "= get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id", "from app.dao.doc import dig_filename_already_exists, dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\", "type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id',", "str(loop))) loop = loop + 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if", "is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc: '", "= doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date", "= get_digfile_row(doc_id) if any(x in docfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']):", "'.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date')", "get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or", "= DigFile() digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id =", "if request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary,", "\"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined = True return docfile", "# digfile.time_date = time_date # digfile.summary = request.form.get('summary') # return digfile # def", "'file' files = docfiles + digfiles + file_store_files results = sorted(files, key=lambda r:", "digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice +", "= datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to", "= datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: # digfile = DigStore() #", "attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = ''", "docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile =", "{'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5", "file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in attachment_details: if", "= doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig ==", "digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles", "file) file_store_file = get_file_store_row(file_id) filepath = os.path.join(mget_filestore_dir(), file_store_file.summary) return Attachment(file_store_file.summary, filepath, 'application/pdf') def", "docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor", "current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients, subject, attachments", "fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments = [] file_list =", "docfile def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type", "= [] # # filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))]", "b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id):", "subject = fdict.get('subject') return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): #", "time_now = datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else:", "file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig): # TODO:", "db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File saved successfully!'", "doc_dig == \"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \"", "object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File saved", "fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id", "pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2 pay_request.doc_dig = 'pr' files", "= attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile)", "in file_list if file.filename] if file_list: if request.form.get('location_db'): for file in file_list: attachment", "def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time()", "docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined = True", "base64 import b64encode def madd_digfile_properties(digfile, doc_form_data): digfile.rent_id = doc_form_data.get('rent_id') digfile.summary = doc_form_data.get('summary') return", "time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id", "file_list if file.filename] if file_list: if request.form.get('location_db'): for file in file_list: attachment =", "uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf')", "# convert HTML to PDF pisa_status = pisa.CreatePDF( source_html, # the HTML to", "= get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles +", "if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop", "+ secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The", "\"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out' return docfiles def", "output file # return False on success and True on errors return pisa_status.err", "# else: # digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date =", "file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename or 'attachment_new.pdf') dig_id, notice =", "fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients':", "get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files = get_file_store_files_for_rent(rent_id) digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files =", "def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date =", "create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig == 'dig': docfile", "def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '') summary = ' '.join([item for item", "docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): # # TODO:", "= digfile_object_create(dig_id) # upload_docfile(digfile) # # return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): #", "file.doc_dig = 'file' files = docfiles + digfiles + file_store_files results = sorted(files,", "# return time_date def docfile_object_create(doc_id, doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "docfile.doc_type = \"in\" docfile.doc_text = \"\" docfile.combined = True return docfile def mget_docfile_combo_meta(rent_id):", "loop + 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else", "# # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id ==", "mupdate_filename_suffix(new_filename) notice = 'File already exists. The new file has been renamed to", "docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request", "attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if file.filename:", "return False on success and True on errors return pisa_status.err def collect_dig_form_data(): rent_id", "'.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file", "= collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file):", "get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.object_id =", "digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''):", "docfile_filter.append(DocFile.rent_id == rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter)", "= summary[0:-3] return summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile,", "'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as", "docfiles: docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig = 'dig' for file", "= \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div + '", "request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int),", "uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit()", "# digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') # digfile.time_date = time_date #", "docfiles + pay_requests return sorted(files, key=lambda r: r.time_date, reverse=True) def mpost_docfile(doc_id, doc_dig): if", "to receive result # close output file result_file.close() # close output file #", "'', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type':", "'.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else: docfile = get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1]", "filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice = '' file_ext = os.path.splitext(filename)[1]", "return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file", "summary): time_date = datetime.now() summary = 'draft-doc: ' + summary docfile = post_docfile(time_date,", "been renamed to ' + filename + '. ' digfile = DigFile() digfile.time_date", "if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text'))))", "'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d')", "get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from base64 import b64encode def madd_digfile_properties(digfile, doc_form_data):", "secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new", "imghdr.what(None, header) if not format: return None return '.' + (format if format", "= get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice =", "saved successfully!' return dig_id, notice # else: # flash('No filename!') # return redirect(request.url)", "digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id", "timedelta from xhtml2pdf import pisa from app import db from flask import current_app,", "docfile_filter = [] file_store_filter = [] fdict = {'dfountin': 'all'} if request.method ==", "else: docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if any(x", "notice = '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date", "+ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id = request.form.get('object_type_id') #", "docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id):", "request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4,", "type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name':", "# close output file result_file.close() # close output file # return False on", "dig_store_filename_already_exists, filename_already_exists, \\ get_docfile_combo_meta, get_docfiles_combo, get_docfile_row, get_docfiles, get_digfile_object, \\ get_digfile_row, get_docfiles_text, get_file_store_row, post_docfile,", "= DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste", "filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc = get_docfile_row(attach_id)", "insert_prs_for_rent(docfiles, rent_id): pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc", "in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf", "== 'attach': for i in range(1, 6): name = 'attachment_' + str(i) fdict[name]", "rename file. Error: {str(ex)}', 'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary", "'Write or paste your document here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles,", "been renamed to ' + filename + '. ' digfile = DigStore() digfile.time_date", "digfile_object_create(dig_id): # # TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id", "== 0: docfile = DocStore() if doc_dig == 'doc' else DigStore time_now =", "'') summary = ' '.join([item for item in summary.split() if '@' not in", "been renamed to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store =", "= request.form.get('object_type_id') # digfile.time_date = time_date # digfile.summary = request.form.get('summary') # return digfile", "1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id else update_docfile(doc_id, is_draft)", "docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date =", "'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details,", "'', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1],", "any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\")", "flask import current_app, flash, request from werkzeug.utils import secure_filename from app.main.common import Attachment,", "docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date", "'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary =", "'doc' else DigStore time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second)", "docfile = create_docfile() elif doc_dig == 'doc': docfile = update_docfile(doc_id) elif doc_dig ==", "filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice", "dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text,", "'', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id': attachment_1[0], 'attach_type': attachment_1[1],", "'all'} if request.method == \"POST\": fdict = mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode'))))", "db from flask import current_app, flash, request from werkzeug.utils import secure_filename from app.main.common", "= open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF pisa_status = pisa.CreatePDF( source_html,", "digfile_filter = [] # # filter out draft docs # docfile_filter = [(DocFile.summary.notlike('%draft-doc:", "file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same", "= imghdr.what(None, header) if not format: return None return '.' + (format if", "= reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to", "attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def", "return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date = datetime.now()", "docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig == 'doc':", "= datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') summary = request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary}", "# digfile.summary = request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None): # time", "= request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0],", "datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if", "attachment_2: attachment_2 = attachment_2.split('$') attachment_2 = {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2)", "docfile.time_date = time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary =", "for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return digfiles, file_store_files def mget_digfile_object(doc_object_id): #", "item in summary.split() if '@' not in item]) if summary[-3:] == ' to':", "rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice = notice + 'File saved", "docfile = DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute,", "'.jpeg', '.bmp']): docfile.image = b64encode(docfile.dig_data).decode(\"utf-8\") elif '.pdf' in docfile.summary: docfile.pdf = b64encode(docfile.dig_data).decode(\"utf-8\") else:", "if not is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined", "docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id", "request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for", "+ digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return results", "is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id')", "file_list: if request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif", "docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste your document here...' docfile.object_id =", "html = attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice", "= request.form.get('summary')[0:89] return {'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id =", "0: # digfile = DigStore() # time_now = datetime.now().time() # time_date = doc_date", "digfile in digfiles: if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg',", "== 'dig': docfile = update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id #", "filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file):", "attach_type == 'doc': attach_doc = get_docfile_row(attach_id) convert_html_to_pdf(attach_doc.doc_text, filename) elif attach_type == 'dig': attach_dig", "seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename): filename = mupdate_filename_suffix(filename)", "def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft", "'', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3, attachment_4, attachment_5]", "attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2:", "# open output file for writing (truncated binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\")", "filename) else: filepath = os.path.join(mget_filestore_dir(), attach_name) return Attachment(attach_name, filepath, mime_type) def mget_attachment_form(): attachments", "docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile)", "out\" or \" out \" in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type =", "docfile.time_date = time_date return docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile,", "def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments = [] file_list = fdict.get('file_list')", "re.sub('\\n', '', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst", "\"Invalid file suffix\" elif file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext", "old_filename, new_filename) return filestore def mupload_docfile_with_attach_info(attachments, docfile): attachment_div = \"<div id='attachments' style='font-size:10.5pt;'>Attachment(s):\" for", "docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \" in \" in", "+ docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date", "seconds=doc_time.second) docfile.object_id = request.form.get('object_id') docfile.object_type_id = request.form.get('object_type_id') docfile.time_date = time_date if doc_dig ==", "object_type_id) def mget_fdict(action=''): fdict = {'rentcode': request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\",", "'', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '', type=str), 'attach_type':", "mget_attachment_form(): attachments = [] attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 =", "file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in file_list: if", "# TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0:", "upload function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time()", "attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '',", "rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice = notice + 'File saved", "0: docfile = DocStore() if doc_dig == 'doc' else DigStore time_now = datetime.now().time()", "{'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if", "pay_requests = get_pr_history(rent_id) for pay_request in pay_requests: pay_request.time_date = pay_request.time_date pay_request.typedoc = 2", "digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return digfile def update_filestore(doc_id): notice = ''", "= doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') # digfile.object_type_id =", "in digfiles: digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig = 'file' files", "'.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id,", "file_list: if file.filename: attachment = create_attachment_save_to_store(rent_id, file) attachments.append(attachment) else: for file in file_list:", "digfile.id db.session.commit() notice = notice + 'File saved successfully!' return dig_id, notice #", "if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else: docfile.in_out = 'out' return docfiles", "return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict = {'rentcode':", "timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile", "exists. The new file has been renamed to ' + filename + '.", "rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date", "= {'attach_id': attachment_1[0], 'attach_type': attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str)", "attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type == 'doc': attach_doc", "def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type':", "file: file.write(attach_dig.dig_data) elif attach_type == 'pr': attach_doc = get_pr_history_row(attach_id) convert_html_to_pdf(attach_doc.block, filename) else: filepath", "file has been renamed to ' + filename + '. ' digfile =", "= 'thread' docfile.summary = 'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles =", "docfiles + digfiles + file_store_files results = sorted(files, key=lambda r: r.time_date, reverse=True) return", "attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop)))", "successfully!' return file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None,", "in file_store_files: file.doc_dig = 'file' files = docfiles + digfiles + file_store_files results", "doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date + timedelta(hours=doc_time.hour,", "digfile.time_date = time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile)", "= time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary')", "mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from app.dao.doc import", "= datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id)", "header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format: return None", "attachment_1[1], 'attach_name': attachment_1[2]} attachments.append(attachment_1) attachment_2 = request.form.get('attachment_2', '', type=str) if attachment_2: attachment_2 =", "time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit()", "create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date')", "attachment_details, fdict = collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list = [file", "= file.time_date.time() if file else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute,", "filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice = notice", "filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def create_attachment_as_temp(uploaded_file): filename = secure_filename(uploaded_file.filename).lower() uploaded_file.save(os.path.join(mget_tempfile_dir(), filename))", "attachment_4 = {'attach_id': request.form.get('attachment_4_id', 0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '',", "+ '. ' digfile = DigStore() digfile.time_date = time_date digfile.summary = filename digfile.dig_data", "to ' + filename + '. ' uploaded_file.save(os.path.join(mget_filestore_dir(), filename)) file_store = FileStore() file_store.time_date", "header) if not format: return None return '.' + (format if format !=", "digfiles: if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg', '.bmp']): digfile.image", "or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb')", "fdict[name] = request.form.get(name) or '' return fdict def mget_new_docfile_object(object_id, object_type_id): docfile = DocStore()", "= rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice = notice + 'File", "= mupdate_filename_suffix(new_filename) notice = 'File already exists. The new file has been renamed", "summary def update_docfile(doc_id, is_draft=False): docfile = get_docfile_row(doc_id) docfile = append_docfile_form_data(docfile, is_draft) return docfile", "attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop + 1 doc_id = fdict.get('doc_id') docfile", "on success and True on errors return pisa_status.err def collect_dig_form_data(): rent_id = int(request.form.get('rent_id'))", "# docfile_filter = [(DocFile.summary.notlike('%draft-doc: %'))] docfile_filter = [] file_store_filter = [] fdict =", "digfile.summary = doc_form_data.get('summary') return digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary", "file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code as rent digfile getter digfile", "get_docfile_object, get_docfile_objects, get_file_store_files_for_rent from app.dao.payrequest import get_pr_history_row, get_pr_history from app.dao.rent import get_rentcode from", "get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile in docfiles: docfile.doc_dig = 'doc' for digfile in", "doc_form_data) return madd_docfile_properties(docfile, doc_form_data, is_draft) def append_filestore_form_data(filestore): filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore,", "appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject = fdict.get('subject') return appmail, docfile, recipients,", "if file.filename] if file_list: if request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id,", "+ summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id def create_docfile(is_draft=False): doc_form_data", "'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)} attachment_details = [attachment_1, attachment_2, attachment_3,", "minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '': notice = '' file_ext", "elif docfile.summary[-4:] == \" out\" or \" out \" in docfile.summary: docfile.doc_type =", "request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form()", "fdict = collect_email_form() attachments = [] file_list = fdict.get('file_list') file_list = [file for", "+ filename + '. ' digfile = DigFile() digfile.time_date = time_date digfile.summary =", "0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id,", "def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file) file_store_file = get_file_store_row(file_id) filepath =", "attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5)", "close output file result_file.close() # close output file # return False on success", "request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int),", "digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return", "\"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action == 'attach':", "filestore_form_data = collect_dig_form_data() filestore = append_file_form_time_data(filestore, filestore_form_data) filestore.rent_id = filestore_form_data.get('rent_id') return filestore def", "attachments.append(attachment) loop = 1 for attachment in attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'),", "# the HTML to convert dest=result_file) # file handle to receive result #", "collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type',", "secure_filename(uploaded_file.filename).lower() if filename != '': notice = '' file_ext = os.path.splitext(filename)[1] if file_ext", "time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id)", "!= old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists. The", "filename + '. ' digfile = DigFile() digfile.time_date = time_date digfile.summary = filename", "= doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if filename != '':", "None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File", "docfile def append_digfile_form_data(digfile): dig_form_data = collect_dig_form_data() digfile = append_file_form_time_data(digfile, dig_form_data) return madd_digfile_properties(digfile, dig_form_data)", "%'))] docfile_filter = [] file_store_filter = [] fdict = {'dfountin': 'all'} if request.method", "redirect(request.url) def mpost_object_upload(object_id, object_type_id, uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date", "docfile.id def create_docfile(is_draft=False): doc_form_data = collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date", "request.form.get(\"rentcode\") or \"\", 'summary': request.form.get(\"summary\") or \"\", 'doc_text': request.form.get(\"doc_text\") or \"\"} if action", "def convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated binary) result_file =", "docfile.time_date = datetime.now() docfile.summary = reset_draft_email_summary(docfile.summary) soup = BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text)", "notice = '' filestore = get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore", "docfile.doc_dig = 'thread' docfile.summary = 'combined doc thread' return docfile def mget_docfiles_combo(rent_id): docfiles", "while filename_already_exists(filename): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The new file", "= attachment_3.split('$') attachment_3 = {'attach_id': attachment_3[0], 'attach_type': attachment_3[1], 'attach_name': attachment_3[2]} attachments.append(attachment_3) attachment_4 =", "docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc',", "result # close output file result_file.close() # close output file # return False", "= datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = secure_filename(uploaded_file.filename).lower() if", "os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath = os.path.join(mget_tempfile_dir(), filename", "{'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog':", "= get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date =", "rent_id) file_store_filter.append(FileStore.rent_id == rent_id) docfiles, digfiles, file_store_files = get_docfiles(docfile_filter, digfile_filter, file_store_filter) for docfile", "time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) # return time_date def docfile_object_create(doc_id, doc_dig):", "request.form.get('attachment_4', '', type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type':", "= get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename", "'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0,", "time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) docfile.time_date = time_date docfile =", "!= validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename)", "update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # # TODO: Refactor # digfile", "\"in\" elif docfile.summary[-4:] == \" out\" or \" out \" in docfile.summary: docfile.doc_type", "import current_app, flash, request from werkzeug.utils import secure_filename from app.main.common import Attachment, mget_filestore_dir,", "doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while", "attachment_1 = request.form.get('attachment_1', '', type=str) if attachment_1: attachment_1 = attachment_1.split('$') attachment_1 = {'attach_id':", "new digital file uses upload function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'),", "# rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date =", "return Attachment(file_store_file.summary, filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name':", "+ filename + '. ' digfile = DigStore() digfile.time_date = time_date digfile.summary =", "doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text", "= attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return attachments", "'error') filestore.summary = old_filename return filestore def reset_draft_email_summary(summary): summary = summary.replace('draft-doc: ', '')", "r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id)", "results = sorted(files, key=lambda r: r.time_date, reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles", "attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name': attachment_5[2]} attachments.append(attachment_5) return", "request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments =", "return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output file", "'.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def", "{'rent_id': rent_id, 'doc_date': doc_date, 'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date =", "doc_dig): # TODO: Refactor doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') if doc_id == 0: docfile", "attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3: attachment_3 = attachment_3.split('$') attachment_3 =", "= 'draft-doc: ' + summary docfile = post_docfile(time_date, doc_text, rent_id, summary) return docfile.id", "'': notice = '' file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return", "mget_fdict(action) if fdict.get('rentcode'): digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'):", "style='font-size:10.5pt;'>Attachment(s):\" for attachment in attachments: attachment_div = attachment_div + ' ' + attachment.file_name", "convert HTML to PDF pisa_status = pisa.CreatePDF( source_html, # the HTML to convert", "= 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type", "type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name',", "dig_id == 0: # digfile = DigStore() # time_now = datetime.now().time() # time_date", "paste your document here...' docfile.object_id = object_id return docfile def insert_prs_for_rent(docfiles, rent_id): pay_requests", "if summary[-3:] == ' to': summary = summary[0:-3] return summary def update_docfile(doc_id, is_draft=False):", "filename digfile.dig_data = uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id", "mget_docfiles_combo(rent_id): docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out", "= append_filestore_form_data(filestore) if new_filename != old_filename: while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice =", "get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second)", "= uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id = digfile.id db.session.commit() notice =", "object_type_id): docfile = DocStore() docfile.time_date = datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write", "docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id = 0", "attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0,", "uploaded_file.save(os.path.join(mget_tempfile_dir(), filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower()", "= {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'),", "in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for file_store_file in file_store_files: file_store_file.ext = os.path.splitext(file_store_file.summary)[1] return", "'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile", "attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop = loop + 1 doc_id =", "for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file", "{'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name': attachment_4[2]} attachments.append(attachment_4) attachment_5 = request.form.get('attachment_5', '', type=str) if", "digfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) docfile_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) file_store_filter.append(Rent.rentcode.ilike('%{}%'.format(fdict.get('rentcode')))) if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action", "0, type=int), 'attach_name': request.form.get('attachment_4_name', '', type=str), 'attach_type': request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id':", "# time_date = doc_date + timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) # digfile.object_id = request.form.get('object_id') #", "if dig_id == 0: # digfile = DigStore() # time_now = datetime.now().time() #", "imghdr import os import re from bs4 import BeautifulSoup from datetime import datetime,", "xhtml2pdf import pisa from app import db from flask import current_app, flash, request", "digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush() dig_id =", "while filename_already_exists(new_filename): new_filename = mupdate_filename_suffix(new_filename) notice = 'File already exists. The new file", "append_docfile_form_data(docfile, is_draft) return docfile def update_digfile(doc_id): digfile = get_digfile_row(doc_id) digfile = append_digfile_form_data(digfile) return", "request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 =", "PDF pisa_status = pisa.CreatePDF( source_html, # the HTML to convert dest=result_file) # file", "int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False):", "def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute,", "return attachment_details, fdict def collect_email_form_data(rent_id, is_draft=False): attachment_details, fdict = collect_email_form() attachments = []", "= doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower()", "if not doc_id else update_docfile(doc_id, is_draft) appmail = current_app.extensions['mail'] recipients = fdict.get('recipients') subject", "mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id", "in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid", "\"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file):", "in attachments: attachment_div = attachment_div + ' ' + attachment.file_name attachment_div = attachment_div", "\"out\" else: docfile.doc_type = \"info\" elif doc_dig == 'dig': docfile = get_digfile_row(doc_id) if", "soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text = str(soup) return email_to, re.sub('\\n', '', subject), docfile.summary", "return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif']", "'.doc', '.docx', '.ods', '.odt', '.jpg', '.png', '.gif'] def append_file_form_time_data(docfile, doc_form_data): doc_time = docfile.time_date.time()", "if file_list: if request.form.get('location_db'): for file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment)", "= madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id): # # TODO: Refactor", "update_digfile(doc_id) else: docfile = update_filestore(doc_id) upload_docfile(docfile) return docfile.rent_id # def mpost_digfile_object(dig_id): # #", "get_file_store_row(doc_id) old_filename = filestore.summary new_filename = request.form.get('summary')[0:89] filestore = append_filestore_form_data(filestore) if new_filename !=", "attachment_details: if attachment.get('attach_id') > 0: attachments.append(mget_attachment(attachment.get('attach_id'), attachment.get('attach_name'), attachment.get('attach_type'), 'attachment_' + str(loop))) loop =", "loop = loop + 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not", "get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id,", "'.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None, \"Invalid image\" while dig_store_filename_already_exists(filename,", "binary) result_file = open(os.path.join(mget_tempfile_dir(), output_filename), \"w+b\") # convert HTML to PDF pisa_status =", "from bs4 import BeautifulSoup from datetime import datetime, timedelta from xhtml2pdf import pisa", "time_date if doc_dig == 'doc': docfile.doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\") docfile.summary = request.form.get('summary') return", "filename or 'attachment_new.pdf') dig_id, notice = mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath,", "timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) else: docfile = get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id)", "attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str) if attachment_3:", "BeautifulSoup(docfile.doc_text, 'html.parser') subject = str(soup.find(id='email_subject_span').text) email_to = soup.find(id='email_to_span') email_to = email_to.string docfile.doc_text =", "'', subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst =", "uploaded_file): doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date + timedelta(hours=time_now.hour,", "'', type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1],", "\"doc\": docfile = get_docfile_row(doc_id) if docfile.summary[-3:] == \" in\" or \" in \"", "if action == 'attach': for i in range(1, 6): name = 'attachment_' +", "collect_doc_form_data() docfile = DocFile() time_now = datetime.now().time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=time_now.hour,", "file_ext = os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None, \"Invalid file suffix\"", "request.form.get('doc_id', 0, int), 'recipients': request.form.get('email_to'), 'save_dig_tog': request.form.get('save_dig_tog'), 'subject': request.form.get('email_subject')} return attachment_details, fdict def", "= doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) #", "docfiles = get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out =", "for digfile in digfiles: digfile.doc_dig = 'dig' for file in file_store_files: file.doc_dig =", "file in file_store_files: file.doc_dig = 'file' files = docfiles + digfiles + file_store_files", "def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile in digfiles: if any(x in digfile.summary for x", "def mget_attachment(attach_id, attach_name, attach_type, filename, mime_type='application/pdf'): filepath = os.path.join(mget_tempfile_dir(), filename) if attach_type ==", "elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") return digfile def mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id)", "= attachment_div + ' ' + attachment.file_name attachment_div = attachment_div + \"</div><br>\" html", "elif action == 'attach' or rent_id > 0: digfile_filter.append(DigFile.rent_id == rent_id) docfile_filter.append(DocFile.rent_id ==", "docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx', '.ods', '.odt',", "new file has been renamed to ' + new_filename + '. ' if", "os.path.splitext(filename)[1] if file_ext not in allowed_filetypes(): return None, \"Invalid file suffix\" elif file_ext", "for docfile in docfiles: docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig =", "request.form.get('doc_combo_true') else False return {'rent_id': rent_id, 'doc_date': doc_date, 'doc_text': doc_text, 'summary': summary, 'combined':", "+ request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes():", "docfile.time_date.time() time_date = doc_form_data.get('doc_date') + \\ timedelta(hours=doc_time.hour, minutes=doc_time.minute, seconds=doc_time.second) docfile.time_date = time_date return", "= FileStore() file_store.time_date = time_date file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush()", "request.form.get('attachment_4_type', '', type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str),", "attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')], 'doc_id': request.form.get('doc_id', 0, int),", "app.main.common import Attachment, mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore,", "file_store.summary = filename file_store.rent_id = rent_id db.session.add(file_store) db.session.flush() file_id = file_store.id db.session.commit() notice", "create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment in attachment_details: if attachment.get('attach_id') > 0:", "'doc_text': doc_text, 'summary': summary, 'combined': combined} def create_draft_email_docfile(doc_text, rent_id, summary): time_date = datetime.now()", "mget_docfile_object(doc_object_id): return get_docfile_object(doc_object_id) def mget_docfile_objects(object_id, object_type_id): return get_docfile_objects(object_id, object_type_id) def mget_fdict(action=''): fdict =", "image\" while dig_filename_already_exists(filename, rent_id): filename = mupdate_filename_suffix(filename) notice = 'File already exists. The", "= doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def allowed_filetypes(): return ['.pdf', '.doc', '.docx',", "# time_date = doc_date + timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) # else: # digfile =", "get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in' else:", "digfile def madd_docfile_properties(docfile, doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not", "Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: # digfile", "= {'attach_id': attachment_2[0], 'attach_type': attachment_2[1], 'attach_name': attachment_2[2]} attachments.append(attachment_2) attachment_3 = request.form.get('attachment_3', '', type=str)", "'summary': summary} def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text =", "datetime.now() docfile.object_type_id = object_type_id docfile.doc_text = 'Write or paste your document here...' docfile.object_id", "digfile = get_digfile_object(doc_object_id) if any(x in digfile.summary for x in ['.png', '.jpg', '.jpeg',", "old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(), new_filename) try: os.rename(src, dst)", "db.session.commit() notice = notice + 'File saved successfully!' return file_id, notice def validate_image(stream):", "type=str)} attachment_5 = {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type',", "'attach_type': request.form.get('attachment_1_type', '', type=str)} attachment_2 = {'attach_id': request.form.get('attachment_2_id', 0, type=int), 'attach_name': request.form.get('attachment_2_name', '',", "\"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice = 'File already", "in docfile.summary: docfile.doc_type = \"out\" else: docfile.doc_type = \"info\" elif doc_dig == 'dig':", "docfile = DocFile() docfile.id = 0 docfile.time_date = datetime.now() docfile.rent_id = int(rent_id) docfile.summary", "' if notice: flash(notice, 'message') filestore = rename_filestore_file(filestore, old_filename, new_filename) return filestore def", "\" in\" or \" in \" in docfile.summary: docfile.doc_type = \"in\" elif docfile.summary[-4:]", "docfile.time_date = time_date docfile = madd_docfile_properties(docfile, doc_form_data, is_draft) return docfile # def digfile_object_create(dig_id):", "= mpost_upload(rent_id, file) dig_row = get_digfile_row(dig_id) with open(filepath, 'wb') as file: file.write(dig_row.dig_data) return", "' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined') return docfile def", "attachments def convert_html_to_pdf(source_html, output_filename): # open output file for writing (truncated binary) result_file", "= uploaded_file.read() digfile.object_id = object_id digfile.object_type_id = object_type_id db.session.add(digfile) db.session.flush() dig_id = digfile.id", "is_draft else 'draft-doc: ' + request.form.get( 'summary')[0:75] docfile.doc_text = doc_form_data.get('doc_text') docfile.combined = doc_form_data.get('combined')", "return digfiles, file_store_files def mget_digfile_object(doc_object_id): # TODO: refactor same code as rent digfile", "# file handle to receive result # close output file result_file.close() # close", "# time = file.time_date.time() if file else datetime.now().time() # time_date = file_date +", "= {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '', type=str), 'attach_type': request.form.get('attachment_1_type', '', type=str)}", "docfile in docfiles: docfile.doc_dig = 'doc' for digfile in digfiles: digfile.doc_dig = 'dig'", "file_id, notice def validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if", "TODO: Refactor # doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') # if dig_id == 0: #", "as file: file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice =", "doc_form_data, is_draft=False): docfile.rent_id = doc_form_data.get('rent_id') docfile.summary = doc_form_data.get('summary') if not is_draft else 'draft-doc:", "file_ext in ['.bmp', '.jpeg', '.jpg', '.png', '.gif'] and file_ext != validate_image(uploaded_file.stream): return None,", "if file else datetime.now().time() # time_date = file_date + timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) #", "file uses upload function # rentcode = request.form.get(\"rentcode\") doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now", "= sorted(files, key=lambda r: r.time_date, reverse=True) return results def mget_dig_and_file_store_data(digfiles, file_store_files): for digfile", "# return docfile.object_id, docfile.object_type_id def mpost_docfile_object(doc_id, doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id,", "def validate_image(stream): header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format:", "return None, \"Invalid image\" while dig_store_filename_already_exists(filename, object_id, object_type_id): filename = mupdate_filename_suffix(filename) notice =", "[attachment_1, attachment_2, attachment_3, attachment_4, attachment_5] fdict = {'file_list': [request.files.get('uploadfile_1'), request.files.get('uploadfile_2'), request.files.get('uploadfile_3'), request.files.get('uploadfile_4'), request.files.get('uploadfile_5')],", "seconds=time_now.second) # else: # digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date", "def collect_doc_form_data(): rent_id = int(request.form.get('rent_id')) doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') doc_text = request.form.get('xinput').replace(\"£\", \"&pound;\")", "get_docfile_object(doc_id) if doc_dig == 'doc' else get_digfile_object(doc_id) doc_time = docfile.time_date.time() time_date = doc_date", "= 'doc' for digfile in digfiles: digfile.doc_dig = 'dig' for file in file_store_files:", "'.jpeg', '.bmp']): digfile.image = b64encode(digfile.dig_data).decode(\"utf-8\") elif '.pdf' in digfile.summary: digfile.pdf = b64encode(digfile.dig_data).decode(\"utf-8\") for", "6): name = 'attachment_' + str(i) fdict[name] = request.form.get(name) or '' return fdict", "Refactor # new digital file uses upload function # rentcode = request.form.get(\"rentcode\") doc_date", "= get_docfiles_combo(rent_id) for docfile in docfiles: if \"in\" in docfile.summary.split(): docfile.in_out = 'in'", "type=str) if attachment_5: attachment_5 = attachment_5.split('$') attachment_5 = {'attach_id': attachment_5[0], 'attach_type': attachment_5[1], 'attach_name':", "= time_date # digfile.summary = request.form.get('summary') # return digfile # def mget_file_time_date(file_date, file=None):", "in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment) loop = 1 for attachment", "file) attachments.append(attachment) else: for file in file_list: if file.filename: attachment = create_attachment_as_temp(file) attachments.append(attachment)", "doc_dig): # TODO: Refactor docfile = docfile_object_create(doc_id, doc_dig) upload_docfile(docfile) return docfile.object_id, docfile.object_type_id def", "'.join([item for item in summary.split() if '@' not in item]) if summary[-3:] ==", "mget_filestore_dir, mget_tempfile_dir, mupdate_filename_suffix from app.models import DigFile, DigStore, DocFile, DocStore, FileStore, Rent from", "elif attach_type == 'dig': attach_dig = get_digfile_row(attach_id) with open(filepath, 'wb') as file: file.write(attach_dig.dig_data)", "file.write(dig_row.dig_data) return Attachment(dig_row.summary, filepath, 'application/pdf') def create_attachment_save_to_store(rent_id, file): file_id, notice = mupload_to_file_store(rent_id, file)", "TODO: Refactor # new digital file uses upload function # rentcode = request.form.get(\"rentcode\")", "docfile.object_type_id def mpost_upload(rent_id, uploaded_file): # TODO: Refactor # new digital file uses upload", "docfile.rent_id = int(rent_id) docfile.summary = \"email in\" docfile.doc_type = \"in\" docfile.doc_text = \"\"", "get_file_store_row(doc_id) docfile.ext = os.path.splitext(docfile.summary)[1] return docfile def mget_new_docfile(rent_id): docfile = DocFile() docfile.id =", "= loop + 1 doc_id = fdict.get('doc_id') docfile = create_docfile(is_draft) if not doc_id", "reverse=True) return results, fdict def mget_doc_and_digfiles(rent_id): docfiles = get_docfiles_text(rent_id) digfiles = get_digfiles_for_rent(rent_id) file_store_files", "docfile.doc_text = html upload_docfile(docfile) def mupload_to_file_store(rent_id, uploaded_file): notice = '' doc_date = datetime.strptime(request.form.get('time_date'),", "fdict.get('subject') return appmail, docfile, recipients, subject, attachments def convert_html_to_pdf(source_html, output_filename): # open output", "file in file_list: attachment = create_attachment_save_to_dig(rent_id, file) attachments.append(attachment) elif request.form.get('location_folder'): for file in", "= '' doc_date = datetime.strptime(request.form.get('time_date'), '%Y-%m-%d') time_now = datetime.now().time() time_date = doc_date +", "type=str) if attachment_4: attachment_4 = attachment_4.split('$') attachment_4 = {'attach_id': attachment_4[0], 'attach_type': attachment_4[1], 'attach_name':", "+ attachment.file_name attachment_div = attachment_div + \"</div><br>\" html = attachment_div + docfile.doc_text docfile.doc_text", "if fdict.get('summary'): digfile_filter.append(DigFile.summary.ilike('%{}%'.format(fdict.get('summary')))) docfile_filter.append(DocFile.summary.ilike('%{}%'.format(fdict.get('summary')))) file_store_filter.append(FileStore.summary.ilike('%{}%'.format(fdict.get('summary')))) if fdict.get('doc_text'): docfile_filter.append(DocFile.doc_text.ilike('%{}%'.format(fdict.get('doc_text')))) elif action == 'attach' or", "new_filename except Exception as ex: flash(f'Cannot rename file. Error: {str(ex)}', 'error') filestore.summary =", "digfile = DigStore() # time_now = datetime.now().time() # time_date = doc_date + timedelta(hours=time_now.hour,", "= time_date digfile.summary = filename digfile.dig_data = uploaded_file.read() digfile.rent_id = rent_id db.session.add(digfile) db.session.flush()", "notice = notice + 'File saved successfully!' return dig_id, notice def prepare_draft_for_edit(docfile): docfile.time_date", "= {'attach_id': request.form.get('attachment_5_id', 0, type=int), 'attach_name': request.form.get('attachment_5_name', '', type=str), 'attach_type': request.form.get('attachment_5_type', '', type=str)}", "summary = ' '.join([item for item in summary.split() if '@' not in item])", "or \"\"} if action == 'attach': for i in range(1, 6): name =", "attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int), 'attach_name': request.form.get('attachment_3_name', '', type=str), 'attach_type': request.form.get('attachment_3_type', '',", "digfile = get_digfile_object(dig_id) # doc_time = digfile.time_date.time() # time_date = doc_date + timedelta(hours=doc_time.hour,", "filepath, 'application/pdf') def collect_email_form(): attachment_1 = {'attach_id': request.form.get('attachment_1_id', 0, type=int), 'attach_name': request.form.get('attachment_1_name', '',", "+ timedelta(hours=time_now.hour, minutes=time_now.minute, seconds=time_now.second) filename = get_rentcode(rent_id) + '-' + secure_filename(uploaded_file.filename).lower() while filename_already_exists(filename):", "subject), docfile.summary def rename_filestore_file(filestore, old_filename, new_filename): src = os.path.join(mget_filestore_dir(), old_filename) dst = os.path.join(mget_filestore_dir(),", "filename)) return Attachment(filename, os.path.join(mget_tempfile_dir(), filename), uploaded_file.content_type) def create_attachment_save_to_dig(rent_id, file): filename = secure_filename(file.filename).lower() filepath", "' + filename + '. ' digfile = DigStore() digfile.time_date = time_date digfile.summary", "digfiles, file_store_files = mget_dig_and_file_store_data(digfiles,file_store_files) files = docfiles + digfiles + file_store_files results =", "request.form.get('attachment_2_name', '', type=str), 'attach_type': request.form.get('attachment_2_type', '', type=str)} attachment_3 = {'attach_id': request.form.get('attachment_3_id', 0, type=int),", "import imghdr import os import re from bs4 import BeautifulSoup from datetime import" ]
[ "== 4 prev_ts = 0.0 for _, _, ts in results: assert ts", "results: assert ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016,", "first_id = unique_id() second_id = unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() ==", "results = list(gen) assert len(results) == 3 prev_ts = 0.0 for _, _,", "results: assert ts > prev_ts prev_ts = ts def test_unique_id(): first_id = unique_id()", "def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results)", "> prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results", "ts > prev_ts prev_ts = ts def test_unique_id(): first_id = unique_id() second_id =", "test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) == 4", "= ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert", "0.0 for _, _, ts in results: assert ts > prev_ts prev_ts =", "= unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() == 64 assert first_id !=", "list(gen) assert len(results) == 3 prev_ts = 0.0 for _, _, ts in", "= video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) == 4 prev_ts =", "second_id = unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() == 64 assert first_id", "video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) == 4 prev_ts = 0.0", "ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results)", "assert ts > prev_ts prev_ts = ts def test_unique_id(): first_id = unique_id() second_id", "video_generator def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert", "_, ts in results: assert ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016):", "def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) ==", "ts in results: assert ts > prev_ts prev_ts = ts def test_unique_id(): first_id", "= ts def test_unique_id(): first_id = unique_id() second_id = unique_id() assert first_id.bit_length() ==", "ts def test_unique_id(): first_id = unique_id() second_id = unique_id() assert first_id.bit_length() == 64", "len(results) == 3 prev_ts = 0.0 for _, _, ts in results: assert", "test_unique_id(): first_id = unique_id() second_id = unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length()", "gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) == 4 prev_ts", "results = list(gen) assert len(results) == 4 prev_ts = 0.0 for _, _,", "ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) == 3 prev_ts = 0.0 for", "= video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) == 3 prev_ts =", "4 prev_ts = 0.0 for _, _, ts in results: assert ts >", "unique_id() second_id = unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() == 64 assert", "path_filelists=filelists_path) results = list(gen) assert len(results) == 3 prev_ts = 0.0 for _,", "pipeline.io import unique_id, video_generator def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results", "ts_format=\"2016\", path_filelists=None) results = list(gen) assert len(results) == 4 prev_ts = 0.0 for", "def test_unique_id(): first_id = unique_id() second_id = unique_id() assert first_id.bit_length() == 64 assert", "= unique_id() second_id = unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() == 64", "prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results =", "prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None) results = list(gen)", "filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) == 3", "_, _, ts in results: assert ts > prev_ts prev_ts = ts def", "ts in results: assert ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen", "assert ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\",", "unique_id() assert first_id.bit_length() == 64 assert second_id.bit_length() == 64 assert first_id != second_id", "in results: assert ts > prev_ts prev_ts = ts def test_unique_id(): first_id =", "prev_ts = ts def test_unique_id(): first_id = unique_id() second_id = unique_id() assert first_id.bit_length()", "path_filelists=None) results = list(gen) assert len(results) == 4 prev_ts = 0.0 for _,", "for _, _, ts in results: assert ts > prev_ts prev_ts = ts", "test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) ==", "3 prev_ts = 0.0 for _, _, ts in results: assert ts >", "from pipeline.io import unique_id, video_generator def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path)", "= list(gen) assert len(results) == 4 prev_ts = 0.0 for _, _, ts", "gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) == 3 prev_ts", "import unique_id, video_generator def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results =", "in results: assert ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen =", "unique_id, video_generator def test_video_generator_2015(bees_video, filelists_path): gen = video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen)", "= list(gen) assert len(results) == 3 prev_ts = 0.0 for _, _, ts", "== 3 prev_ts = 0.0 for _, _, ts in results: assert ts", "prev_ts = 0.0 for _, _, ts in results: assert ts > prev_ts", "list(gen) assert len(results) == 4 prev_ts = 0.0 for _, _, ts in", "= 0.0 for _, _, ts in results: assert ts > prev_ts prev_ts", "_, ts in results: assert ts > prev_ts prev_ts = ts def test_unique_id():", "> prev_ts prev_ts = ts def test_unique_id(): first_id = unique_id() second_id = unique_id()", "assert len(results) == 3 prev_ts = 0.0 for _, _, ts in results:", "ts > prev_ts prev_ts = ts def test_video_generator_2016(bees_video_2016): gen = video_generator(bees_video_2016, ts_format=\"2016\", path_filelists=None)", "prev_ts prev_ts = ts def test_unique_id(): first_id = unique_id() second_id = unique_id() assert", "assert len(results) == 4 prev_ts = 0.0 for _, _, ts in results:", "len(results) == 4 prev_ts = 0.0 for _, _, ts in results: assert", "video_generator(bees_video, ts_format=\"2015\", path_filelists=filelists_path) results = list(gen) assert len(results) == 3 prev_ts = 0.0" ]
[ "test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def", "def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def", "output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output", "fiasko_bro import defaults from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output", "= defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip", "from fiasko_bro import defaults from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip']", "directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip)", "fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert", "file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output =", "directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path,", "<gh_stars>10-100 from fiasko_bro import defaults from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip =", "str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is", "= file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output", "import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output,", "= file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output =", "defaults from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path,", "directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip", "None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert output is", "file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path,", "output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251']", "defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip =", "from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip)", "def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None", "isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output", "test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path):", "output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert", "def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert output is None", "import defaults from fiasko_bro.pre_validation_checks import file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output =", "= defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip =", "assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip)", "is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path): directories_to_skip = ['win1251'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert output", "defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip']", "directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert output is None def test_file_not_in_utf8_uses_whitelist(encoding_repo_path):", "file_not_in_utf8 def test_file_not_in_utf8_fail(encoding_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(encoding_repo_path, directories_to_skip) assert isinstance(output, str)", "assert isinstance(output, str) def test_file_not_in_utf8_ok(general_repo_path): directories_to_skip = defaults.VALIDATION_PARAMETERS['directories_to_skip'] output = file_not_in_utf8(general_repo_path, directories_to_skip) assert" ]
[ "def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols)", "from unittest import TestCase from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class", "'+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value',", "TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def", "test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values =", "TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n|", "|\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value',", "|value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col',", "|value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '|", "unittest import TestCase from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase):", "TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3", "self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self):", "'| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols", "|\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '| col", "test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) )", "self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '|", "entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n| val", ") self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual(", "[ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n| val |field|val3 |\\n+-----+-----+-----+\\n',", "col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual(", "TestCase from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self):", "values = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual(", "class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self):", "'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [", "test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2)", "from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '',", "<filename>tests/test_ds_simple_db/test_serializers/test_table_serializer.py from unittest import TestCase from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer", "test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n|", "self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val',", "import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = []", "'| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field',", "= ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n',", "[] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n',", ") def test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n',", "'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols =", "'+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value', 'col3']", "['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols", "def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols)", "self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col', 'value',", "self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1)", "def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n',", "cols = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def", "def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3", "'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries =", "value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n| val |field|val3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5).entries_to_string(entries) )", "= ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self):", "['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries", "= ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self):", "'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def test_get_row(self): cols = ['col',", "self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n|", "= [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n| val |field|val3", "from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries", "entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) )", "Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n| val |field|val3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5).entries_to_string(entries)", "|value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ]", "ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries =", "Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual(", "TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3", "import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) )", "test_get_row(self): cols = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) )", "cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) ) def", "col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')),", ") def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual( '+-----+-----+-----+\\n| col", "TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value', 'col3']", "= [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual(", "import TestCase from ds_simple_db.core.entry import Entry from ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def", "def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values)", "TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3", "['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values)", ") def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n',", "self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col',", "col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols =", "'', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) )", "test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_header(cols) )", "TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual(", "'+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value', 'col3'] self.assertEqual( '| col", "'value', 'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) )", "def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values", "'col3'] self.assertEqual( '| col |value|col3 |\\n', TableSerializer(row_width=5)._get_row_content(values) ) self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def", "ds_simple_db.serializers.table_serializer import TableSerializer class TestTableSerializer(TestCase): def test_entries_to_string_empty_entries_returns_empty_string(self): entries = [] self.assertEqual( '', TableSerializer().entries_to_string(entries)", "|\\n+-----+-----+-----+\\n', TableSerializer(row_width=5)._get_row(cols) ) def test_entries_to_string(self): entries = [ Entry(data=dict(col='val', value='field', col3='val3')), ] self.assertEqual(", "TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self): values = ['col', 'value', 'col3']", ") self.assertEqual( '|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual(", ") def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col |value|col3 |\\n+-----+-----+-----+\\n',", "'|col|val|col|\\n', TableSerializer(row_width=3)._get_row_content(values) ) def test_get_header(self): cols = ['col', 'value', 'col3'] self.assertEqual( '+-----+-----+-----+\\n| col", "TableSerializer().entries_to_string(entries) ) def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def", ") def test_row_separator(self): self.assertEqual( '+-----+-----+\\n', TableSerializer(row_width=5)._get_row_separator(num_cols=2) ) self.assertEqual( '+---+\\n', TableSerializer(row_width=3)._get_row_separator(num_cols=1) ) def test_get_row_content(self):" ]
[ "Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint = new_tint self.__update_card_image() return True", "self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None if", "size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self): return", "self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w,", "image = PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img * self._field_tint if", "= font.create_image(text, color) else: self._field_label = None self.__update_card_image() return True def get_text(self): return", "= self.min_size w = field_width + l + r size = (w, h)", "True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update =", "l, r, b, t = self.inner_borders w, h = self.min_size w = field_width", "else: task() def set_field_tint(self, tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if", "item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1:", "get_item_text(self, item_id): if item_id not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id,", "self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not", "0, 0, 0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0,", "if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image", "y = self.get_pos() w, h = self.get_size() img = PNMImage(w, h, 4) parent_img", "composed=False): field = self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height", "field = self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height =", "task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint = tint if", "self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index,", "get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if", "not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def", "False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text", "select_initial and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text)", "None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active: self.active =", "allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text == text: return False", "= icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else:", "None and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item,", "x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def get_image(self,", "self._item_ids = [] self._item_texts = {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers", "+ offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id:", "y, w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled", "4) if draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label: x, y =", "self._items[item_id] if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True)", "= width - l - r h = height - b - t", "= True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height =", "= self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if item_id", "set_field_tint(self, tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint:", "return image def get_image(self, state=None, composed=False): field = self._input_field if not field or", "offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x + offset_x, y", "get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids", "else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint = new_tint self.__update_card_image() return", "if self._selected_item_id == item_id: self._selected_item_id = None if index == size - 1:", "- 1: index -= 1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if", "= False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text:", "return False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \"", "0, 0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task = self.__card_update_task if", "self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not None", "get_image(self, state=None, composed=False): field = self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state)", "4) field_img = field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y,", "or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field", "x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state, draw_field=False)", "True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x +", "= self._input_field if not field or field.is_hidden() != show: return False r =", "self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True", "self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0,", "parent: return x, y = self.get_pos() w, h = self.get_size() img = PNMImage(w,", "if self.is_hidden(): return image = self.get_image(composed=False) if not image: return parent = self.parent", "state=None, composed=False): field = self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width,", "self._input_field = None if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color =", "* self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0)", "= item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index,", "= None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w, h", "self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width,", "text): if self._field_text == text: return False self._field_text = text if self._field_text_in_tooltip and", "not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image = PNMImage(width,", "width, height = self.get_size() image = PNMImage(width, height, 4) field_img = field.get_image() if", "= self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id", "color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None self.__update_card_image() return", "None if index == size - 1: index -= 1 if index >=", "return self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img = image def __get_image(self,", "(x + offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h =", "item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item =", "self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id =", "self._popup_menu.update() def remove_item(self, item_id): if item_id not in self._item_ids: return item = self._items[item_id]", "None self.set_text(\"\") def select_item(self, item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]() def", "self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self._is_field_active = False self._field_back_img", "self._field_text == text: return False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text", "self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field", "(x + offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id):", "offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos", "is not None and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item =", "y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return", "and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index)", "update = False if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items:", "x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y = self.get_field_offset()", "self._selected_item_id if sel_item_id is not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field", "return width, height def has_icon(self): return self._combo_icon is not None def set_field_back_image(self, image):", "self._selection_handlers = {} self._is_field_active = False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field", "x, y, w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale()", "self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self,", "if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item", "return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text", "if item_id not in self._item_ids: return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id]", "= None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text = Skin.text[\"combobox\"]", "field.show() if show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field", "self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if not", "self.get_size() image = PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img * self._field_tint", "w = field_width + l + r size = (w, h) self.set_size(size, is_min=True)", "item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None if index == size -", "sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu =", "y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img,", "None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False)", "h) self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self): return self._combo_icon is not", "- r h = height - b - t size = (w, h)", "import * from .button import Button from .menu import Menu class ComboBox(Button): _ref_node", "self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active: self.active = False self.on_leave(force=True)", "= self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def get_image(self, state=None, composed=False):", "if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint = new_tint", "input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer", "self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide)", "def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu", "if item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self):", "= self._selected_item_id if sel_item_id is not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy()", ".25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r,", "self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update()", "self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None", "= item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if item_id not in", "return True def select_none(self): if self._selected_item_id is not None and self._selected_item_id not in", "item_id: return update = False if self._selected_item_id is not None and self._selected_item_id not", "index == size - 1: index -= 1 if index >= 0: self.select_item(self._item_ids[index])", "return False self._field_tint = new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id is", "offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id: return", "= {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if not", "self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if text else \"\"))", "if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field)", "PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled", "self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if", "self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text == text: return False self._field_text", "True def select_none(self): if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items:", "item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id", "sel_item_id = self._selected_item_id if sel_item_id is not None and sel_item_id not in self._persistent_items:", "self._popup_menu = None def __on_hide(self): if self.active: self.active = False self.on_leave(force=True) def __show_menu(self):", "self.get_pos() w, h = self.get_size() img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False)", "= img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0.,", "self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id])", "text if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else:", "if sel_item_id is not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field =", "parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image, 0, 0, 0, 0)", "if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not in self._item_ids:", "self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None,", "if icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4)", "input_field): self._input_field = input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size", "self.__update_card_image() return True def get_text(self): return self._field_text def set_item_text(self, item_id, text): if item_id", "self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min)", "y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0,", "selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id):", "PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y,", "and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if", "if self._field_text == text: return False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text:", "image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def get_image(self, state=None, composed=False): field =", "self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in self._persistent_items or self._selected_item_id != item_id:", "+ offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if", "x, y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0)", "len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update:", "self._item_texts = {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\")", "height, 4) if draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label: x, y", "self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field if not field or field.is_hidden():", "= \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint", "+ (\": \" + text if text else \"\")) if text: skin_text =", "\"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip = True", "new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False", "field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command", "None def __on_hide(self): if self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if not", "self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text", "item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self,", "self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip", "= self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders", "not image: return parent = self.parent if not parent: return x, y =", "def set_item_index(self, item_id, index): if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id)", "not in self._item_ids: return self._item_texts[item_id] = text if item_id in self._persistent_items or self._selected_item_id", "__show_menu(self): if not self._popup_menu.items: return self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x,", "= PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x,", ">= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update()", "0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def", "= text self._field_text_in_tooltip = True self._items = {} self._item_ids = [] self._item_texts =", "field or field.is_hidden() != show: return False r = field.show() if show else", "self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def get_image(self, state=None, composed=False): field", "0, 0) return image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True):", "= False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active = True x,", "self._item_ids: return self._item_texts[item_id] = text if item_id in self._persistent_items or self._selected_item_id != item_id:", "0, 0, 0, 0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y,", "= (w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self): return self._combo_icon", "return update = False if self._selected_item_id is not None and self._selected_item_id not in", "text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text,", "not self._popup_menu.items: return self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y =", "h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon = img self._combo_icon_disabled", "in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True", "image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0,", "def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy()", "self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y,", "text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu", "if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def", "== item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not in self._item_ids: return return", "index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\")", "self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu =", "text: return False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\":", "if not image: return parent = self.parent if not parent: return x, y", "text if text else \"\")) if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"]", "+ l + r size = (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self)", "0, 0) return image def get_image(self, state=None, composed=False): field = self._input_field if not", "w, h = self.get_size() img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if", "self._input_field: l, r, b, t = self.inner_borders w = width - l -", "not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in", "None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w, h =", "item = self._items[item_id] if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item,", "alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id: return update = False if", "pos = (x + offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w,", "index): if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id]", "self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else:", "else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id):", "not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None", "y + offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id ==", "width, height def has_icon(self): return self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img", "= self.get_size() image = PNMImage(width, height, 4) field_img = field.get_image() if field_img: x,", "self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if not field or field.is_hidden() !=", "0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image", "self.__update_card_image() return True def select_none(self): if self._selected_item_id is not None and self._selected_item_id not", "set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min) if self._input_field:", "= self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size =", "Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def clear(self):", "\"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint =", "if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def", "True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self,", "offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x + offset_x,", "def input_field(self, input_field): self._input_field = input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size", "= text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if", "def has_icon(self): return self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img = image", "show: return False r = field.show() if show else field.hide() self.__update_card_image() return r", "if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id)", "x, y = self.get_pos() w, h = self.get_size() img = PNMImage(w, h, 4)", "and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if text else \"\")) if", "self._item_texts[item_id] = text if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text,", "= self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x, y +", "return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids =", "offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id", "image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x,", "icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b,", "item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None", "menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items =", "= self.get_pos() w, h = self.get_size() img = PNMImage(w, h, 4) parent_img =", "4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon = img self._combo_icon_disabled =", "image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id,", "item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return", "= Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x, y", "0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if", "= new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id is not None and", "t = self.inner_borders w = width - l - r h = height", "l - r h = height - b - t size = (w,", "h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id: return update =", "image def __get_image(self, state=None, draw_field=True): width, height = self.get_size() image = PNMImage(width, height,", "= menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items", "font.create_image(text, color) else: self._field_label = None self.__update_card_image() return True def get_text(self): return self._field_text", "self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu", "= self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if", "if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label =", "self.is_hidden(): return image = self.get_image(composed=False) if not image: return parent = self.parent if", "height = self.get_size() image = PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img", "\" + text if text else \"\")) if text: skin_text = Skin.text[\"combobox\"] font", "item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if", "allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text == text: return", "not None and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id]", "index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item", "parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\"", "if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if text else", "= self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id", "remove_item(self, item_id): if item_id not in self._item_ids: return item = self._items[item_id] del self._items[item_id]", "None def set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None, draw_field=True): width, height", "img, w, h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\"", "Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r, b, t = self.inner_borders w", "field_back_img = self._field_back_img * self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x,", "select_none(self): if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index =", "if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id)", "self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip = True self._items = {}", "if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def", "0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task = self.__card_update_task", "size, includes_borders, is_min) if self._input_field: l, r, b, t = self.inner_borders w =", "_ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent,", "0, 0, x, y, w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled =", "= self.parent if not parent: return x, y = self.get_pos() w, h =", "item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id:", "item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id)", "h = height - b - t size = (w, h) self._input_field.set_size(size, includes_borders,", "item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if not persistent:", "self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x + offset_x, y + offset_y", "width - l - r h = height - b - t size", "= PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label:", "select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda:", "def set_field_tint(self, tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint ==", "= None self.__update_card_image() return True def get_text(self): return self._field_text def set_item_text(self, item_id, text):", "in self._item_ids: return self._item_texts[item_id] = text if item_id in self._persistent_items or self._selected_item_id !=", "text else \"\")) if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color =", "None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text = Skin.text[\"combobox\"] font", "self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self,", "includes_borders, is_min) if self._input_field: l, r, b, t = self.inner_borders w = width", "+ offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size()", "self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or", ".base import * from .button import Button from .menu import Menu class ComboBox(Button):", "= None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active: self.active", "self._field_text_in_tooltip = True self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items", "self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image", "__on_hide(self): if self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return", "draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label,", "def select_item(self, item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return", "= self.get_image(composed=False) if not image: return parent = self.parent if not parent: return", "0) return image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item", "self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids)", "True def get_text(self): return self._field_text def set_item_text(self, item_id, text): if item_id not in", "r = field.show() if show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field", "offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x +", "PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon = img", "h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id,", "field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0,", "return image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item =", "def get_item_text(self, item_id): if item_id not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self,", "= self._input_field if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size()", "in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not in", "== size - 1: index -= 1 if index >= 0: self.select_item(self._item_ids[index]) else:", "self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if", "h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not", "self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image", "item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id]", "(w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is", "* from .button import Button from .menu import Menu class ComboBox(Button): _ref_node =", "__card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if not image: return parent =", "parent = self.parent if not parent: return x, y = self.get_pos() w, h", "skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None self.__update_card_image() return True def", "get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow", "img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon", "PNMImage(width, height, 4) field_img = field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img,", "self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if item_id not in self._item_ids: return", "{} self._item_ids = [] self._item_texts = {} self._persistent_items = [] self._selected_item_id = None", "if self._field_tint == new_tint: return False self._field_tint = new_tint self.__update_card_image() return True def", "not in self._item_ids: return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id]", "= (x + offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos) def __on_select(self,", "height, 4) field_img = field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x,", "if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image, 0, 0, 0,", ".menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids,", "state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x, y = self.get_icon_offset()", "persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if", "+ r size = (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id =", "alt_pos = (x + offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos) def", "def get_image(self, state=None, composed=False): field = self._input_field if not field or field.is_hidden(check_ancestors=False): return", "self._field_tint = new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id is not None", "t = self.inner_borders w, h = self.min_size w = field_width + l +", "= Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w,", "index, update=True) @property def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field =", "w = width - l - r h = height - b -", "def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text == text:", "= self.get_size() img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img,", "draw_field=True): width, height = self.get_size() image = PNMImage(width, height, 4) if draw_field: field_back_img", "self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active: self.active = False", "self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if text else \"\")) if text:", "update=True) @property def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field", "def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field if not", "= None if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"]", "4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h)", "self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if not image: return", "self._field_text def set_item_text(self, item_id, text): if item_id not in self._item_ids: return self._item_texts[item_id] =", "= image def __get_image(self, state=None, draw_field=True): width, height = self.get_size() image = PNMImage(width,", "image): self._field_back_img = image def __get_image(self, state=None, draw_field=True): width, height = self.get_size() image", "else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t", "return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def", "self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field @input_field.setter", "return self.__get_image(state) width, height = self.get_size() image = PNMImage(width, height, 4) field_img =", "update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def", "return parent = self.parent if not parent: return x, y = self.get_pos() w,", "item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None:", "persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id]", "__get_image(self, state=None, draw_field=True): width, height = self.get_size() image = PNMImage(width, height, 4) if", "tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint = new_tint self.__update_card_image()", "self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id =", "if item_id not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index): if", "color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None if icon_id:", "= skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None if icon_id: x,", "tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return", "= self.inner_borders w = width - l - r h = height -", "not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def set_size(self, size,", "item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size", "h = self._popup_menu.get_size() alt_pos = (x + offset_x, y + offset_y - h)", "if self._selected_item_id == item_id: return update = False if self._selected_item_id is not None", "color) else: self._field_label = None self.__update_card_image() return True def get_text(self): return self._field_text def", "= sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if not field or", "self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text = Skin.text[\"combobox\"] font =", "gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text =", "= self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id !=", "image = PNMImage(width, height, 4) field_img = field.get_image() if field_img: x, y =", "= len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True,", "self._field_back_img * self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0,", "field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image = PNMImage(width, height, 4) field_img", "def is_input_field_hidden(self): field = self._input_field if not field or field.is_hidden(): return True return", "= PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon =", "or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id:", "y, 0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0)", "return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in self._persistent_items or self._selected_item_id", "return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def", "l + r size = (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id", "= None if index == size - 1: index -= 1 if index", "self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field if not self.sizer: sizer =", "index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self):", "\"\")) if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label", "field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img", "import Button from .menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self,", "= self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img,", "index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id =", "= field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0)", "new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id is not None and self._selected_item_id", "self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id: return update = False", "def set_text(self, text): if self._field_text == text: return False self._field_text = text if", "self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id != item_id:", "+ text if text else \"\")) if text: skin_text = Skin.text[\"combobox\"] font =", "else: self._field_label = None self.__update_card_image() return True def get_text(self): return self._field_text def set_item_text(self,", "x, y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0)", "return self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field if not self.sizer: sizer", "item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not in self._item_ids: return return self._item_texts[item_id]", "if self._input_field: l, r, b, t = self.inner_borders w = width - l", "= (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id", "return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True):", "= field_width + l + r size = (w, h) self.set_size(size, is_min=True) def", "update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if item_id not in self._item_ids:", "self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y =", "- h) self._popup_menu.show(pos, alt_pos) def __on_select(self, item_id): if self._selected_item_id == item_id: return update", "y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x, y", "includes_borders, is_min) return width, height def has_icon(self): return self._combo_icon is not None def", "def get_text(self): return self._field_text def set_item_text(self, item_id, text): if item_id not in self._item_ids:", "self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active = True x, y =", "persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id", "destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None if index ==", "Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items = []", "or field.is_hidden() != show: return False r = field.show() if show else field.hide()", "in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True,", "r h = height - b - t size = (w, h) self._input_field.set_size(size,", "w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x,", "= [] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden():", "width, height = Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r, b, t", "if text else \"\")) if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color", "return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not in self._item_ids: return self._item_ids.remove(item_id)", "None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial", "self.inner_borders w = width - l - r h = height - b", "import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\",", "= \"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip =", "self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x, y + offset_y)", "self._input_field if not field or field.is_hidden() != show: return False r = field.show()", "field_width self._field_text = text self._field_text_in_tooltip = True self._items = {} self._item_ids = []", "= None self._selection_handlers = {} self._is_field_active = False self._field_back_img = None self._field_tint =", "not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids", "has_icon(self): return self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img = image def", "parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image, 0, 0,", "self.set_text(\"\") def select_item(self, item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self):", "from .base import * from .button import Button from .menu import Menu class", "y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img", "= field.show() if show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field =", "= True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x", "index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items:", "False if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index =", "is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r, b,", "= None if icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w,", "Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\",", "self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self): return self._combo_icon is not None", "set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None, draw_field=True): width, height = self.get_size()", "= None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image =", "def set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None, draw_field=True): width, height =", "self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if", "if not field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image =", "w, h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task,", "is_input_field_hidden(self): field = self._input_field if not field or field.is_hidden(): return True return False", "self.set_text(text) def get_item_text(self, item_id): if item_id not in self._item_ids: return return self._item_texts[item_id] def", "self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in", "parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text", "= allow def set_text(self, text): if self._field_text == text: return False self._field_text =", "self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in", "[] self._item_texts = {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {}", "sel_item_id is not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None", "y, 0, 0) return image def get_image(self, state=None, composed=False): field = self._input_field if", "size = (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if", "in self._item_ids: return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index", "self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update", "item_id not in self._item_ids: return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del", "def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type", "def remove_item(self, item_id): if item_id not in self._item_ids: return item = self._items[item_id] del", "= None def __on_hide(self): if self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if", "offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x, y + offset_y) offset_x,", "def __get_image(self, state=None, draw_field=True): width, height = self.get_size() image = PNMImage(width, height, 4)", "tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text = text", "img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25)", "self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active: self.active = False self.on_leave(force=True) def", "= self.get_menu_offset(\"bottom\") pos = (x + offset_x, y + offset_y) offset_x, offset_y =", "index -= 1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in", "Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not None and sel_item_id not in", "r, b, t = self.inner_borders w = width - l - r h", "Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x, y =", "sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint = tint if tint", "w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -=", "self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else:", "if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy()", "= Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items =", "return True def get_text(self): return self._field_text def set_item_text(self, item_id, text): if item_id not", "font.create_image(text, color) else: self._field_label = None if icon_id: x, y, w, h =", "add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command,", "self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items", "skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color)", "self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) ==", "if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def", "== item_id: self._selected_item_id = None if index == size - 1: index -=", "field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field if not field or", "height = Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r, b, t =", "0, 0, 0, 0) return image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False,", "size - 1: index -= 1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\")", "w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self):", "h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w,", "item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def", "update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self,", "if draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label: x, y = self.get_field_label_offset()", "item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is", "return self._item_texts[item_id] = text if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id,", "self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text)", "= True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update", "= {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def", "[] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return", "@property def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field if", "None self.__update_card_image() return True def get_text(self): return self._field_text def set_item_text(self, item_id, text): if", "= self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else:", "width, height = self.get_size() image = PNMImage(width, height, 4) if draw_field: field_back_img =", "y, w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h) def", "Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color", "item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update:", "return image = self.get_image(composed=False) if not image: return parent = self.parent if not", "else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return", "img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image def add_item(self,", "self._selected_item_id = None self._selection_handlers = {} self._is_field_active = False self._field_back_img = None self._field_tint", "allow def set_text(self, text): if self._field_text == text: return False self._field_text = text", "LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu =", "0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img =", "self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not in self._item_ids: return", "icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image,", "field or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image = PNMImage(width, height,", "Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width = field_width", "item_id: self._selected_item_id = None if index == size - 1: index -= 1", "return return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not in self._item_ids: return", "= self._popup_menu.get_size() alt_pos = (x + offset_x, y + offset_y - h) self._popup_menu.show(pos,", "return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id)", "item_id): if item_id not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index):", "self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False):", "if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property", "color) else: self._field_label = None if icon_id: x, y, w, h = Skin.atlas.regions[icon_id]", "lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text", "{} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self):", "= skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None self.__update_card_image() return True", "sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True):", "if not field or field.is_hidden() != show: return False r = field.show() if", "w, h = self._popup_menu.get_size() alt_pos = (x + offset_x, y + offset_y -", "= height - b - t size = (w, h) self._input_field.set_size(size, includes_borders, is_min)", "def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {}", "self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True)", "self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self):", "+ offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x", "{} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self._is_field_active = False", "y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self, state, composed=False)", "x, y, w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h)", "= tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint", "self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb()", "state=None, draw_field=True): width, height = self.get_size() image = PNMImage(width, height, 4) if draw_field:", "self._field_width = field_width self._field_text = text self._field_text_in_tooltip = True self._items = {} self._item_ids", "{} self._is_field_active = False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None", "self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text)", "self.min_size w = field_width + l + r size = (w, h) self.set_size(size,", "self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text =", "self.__get_image(state) width, height = self.get_size() image = PNMImage(width, height, 4) field_img = field.get_image()", "not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id", "return self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos", "= self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image def add_item(self, item_id,", "if self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active", "self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos =", "not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id):", "is_min) return width, height def has_icon(self): return self._combo_icon is not None def set_field_back_image(self,", "text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def", "def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip =", "self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0,", "Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w, h = self.min_size w =", "def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text):", "self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in self._persistent_items or self._selected_item_id !=", "input_field(self, input_field): self._input_field = input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size =", "in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id", "self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item", "item_id, text): if item_id not in self._item_ids: return self._item_texts[item_id] = text if item_id", "item_id not in self._item_ids: return self._item_texts[item_id] = text if item_id in self._persistent_items or", "update = True if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height", "x, y, 0, 0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0,", "set_text(self, text): if self._field_text == text: return False self._field_text = text if self._field_text_in_tooltip", "in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id]", "0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return", "y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos =", "self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return", "Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h)", "Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label", "- b - t size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return width,", "= PNMImage(width, height, 4) field_img = field.get_image() if field_img: x, y = self.get_field_offset()", "self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide)", "field_img = field.get_image() if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0,", "self._field_label = font.create_image(text, color) else: self._field_label = None self.__update_card_image() return True def get_text(self):", "item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] =", "index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if item_id not in", "self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if item_id", "def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return", "img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x,", "is not None def set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None, draw_field=True):", "def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text,", "self._popup_menu.get_size() alt_pos = (x + offset_x, y + offset_y - h) self._popup_menu.show(pos, alt_pos)", "= self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x,", "False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active = True x, y", "def set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min) if", "self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self,", "image.blend_sub_image(img, 0, 0, 0, 0) return image def add_item(self, item_id, item_text, item_command=None, index=None,", "= self.get_menu_offset(\"top\") w, h = self._popup_menu.get_size() alt_pos = (x + offset_x, y +", "== 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update()", "= self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def", "self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w, h = self.min_size", "icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None", "self.get_size() image = PNMImage(width, height, 4) field_img = field.get_image() if field_img: x, y", "t size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self):", "if show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field if", "- t size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height def", "0, 0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0)", "self.parent if not parent: return x, y = self.get_pos() w, h = self.get_size()", "self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial and", "self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def", "= Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else:", "self.get_size() img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0,", "item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def", "0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image def", "def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1,", "del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id", "height = self.get_size() image = PNMImage(width, height, 4) field_img = field.get_image() if field_img:", "= None self.set_text(\"\") def select_item(self, item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]()", "self._field_label = None self.__update_card_image() return True def get_text(self): return self._field_text def set_item_text(self, item_id,", "self.get_menu_offset(\"bottom\") pos = (x + offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\")", "size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id,", "0, x, y, w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w,", "self._is_field_active = False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if", "item_id not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id", "= font.create_image(text, color) else: self._field_label = None if icon_id: x, y, w, h", "self._field_text = text self._field_text_in_tooltip = True self._items = {} self._item_ids = [] self._item_texts", "show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field if not", "from .button import Button from .menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\")", "= text if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True)", "= NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids,", "= {} self._is_field_active = False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"] self._input_field =", "if field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img =", "False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" +", "show=True): field = self._input_field if not field or field.is_hidden() != show: return False", "self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id ==", ".button import Button from .menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def", "(w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height def has_icon(self): return self._combo_icon is", "self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if item_id not in self._item_ids: return", "else \"\")) if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"]", "icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width", "= Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r, b, t = self.inner_borders", "not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update =", "False r = field.show() if show else field.hide() self.__update_card_image() return r def is_input_field_hidden(self):", "self.active = False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active = True", "self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if not field", "if index == size - 1: index -= 1 if index >= 0:", "image = self.get_image(composed=False) if not image: return parent = self.parent if not parent:", "includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min) if self._input_field: l, r,", "self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if", "get_text(self): return self._field_text def set_item_text(self, item_id, text): if item_id not in self._item_ids: return", "= Menu(on_hide=self.__on_hide) l, r, b, t = self.inner_borders w, h = self.min_size w", "None if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label", "or field.is_hidden(check_ancestors=False): return self.__get_image(state) width, height = self.get_size() image = PNMImage(width, height, 4)", "None self._selection_handlers = {} self._is_field_active = False self._field_back_img = None self._field_tint = Skin.colors[\"combobox_field_tint_default\"]", "index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id", "field_img: x, y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state,", "def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not None and sel_item_id", "0) img = Button.get_image(self, state, composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon:", "skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None if", "0, 0, 0) return image def add_item(self, item_id, item_text, item_command=None, index=None, persistent=False, update=False,", "self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field @input_field.setter def input_field(self, input_field):", "@input_field.setter def input_field(self, input_field): self._input_field = input_field if not self.sizer: sizer = Sizer(\"horizontal\")", "task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None):", "item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id)", "self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if item_id", "self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id", "r size = (w, h) self.set_size(size, is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id", "return self._field_text def set_item_text(self, item_id, text): if item_id not in self._item_ids: return self._item_texts[item_id]", "l, r, b, t = self.inner_borders w = width - l - r", "w, h = self.min_size w = field_width + l + r size =", "(\": \" + text if text else \"\")) if text: skin_text = Skin.text[\"combobox\"]", "self._field_back_img = image def __get_image(self, state=None, draw_field=True): width, height = self.get_size() image =", "not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear()", "in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id =", "= Skin.colors[\"combobox_field_tint_default\"] self._input_field = None if text: skin_text = Skin.text[\"combobox\"] font = skin_text[\"font\"]", "{} self.set_text(\"\") def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if not image:", "-= 1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items:", "update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders,", "self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0.,", "tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width =", "= self.get_size() image = PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img *", "0) return image def get_image(self, state=None, composed=False): field = self._input_field if not field", "self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image def add_item(self, item_id, item_text,", "= PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon =", "img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task =", "if update: self._popup_menu.update() def set_size(self, size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size,", "font = skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label =", "self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self): if self.active:", "sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field", "del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items", "size, includes_borders=True, is_min=False): width, height = Button.set_size(self, size, includes_borders, is_min) if self._input_field: l,", "update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None if index", "self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items: return self.active =", "img.copy_sub_image(Skin.atlas.image, 0, 0, x, y, w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled", "self._selected_item_id = None if index == size - 1: index -= 1 if", "task() def set_field_tint(self, tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint", "b - t size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return width, height", "or self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if", "if not self._popup_menu.items: return self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y", "set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu", "image: return parent = self.parent if not parent: return x, y = self.get_pos()", "if item_id not in self._item_ids: return self._item_texts[item_id] = text if item_id in self._persistent_items", "self._popup_menu.items: return self.active = True x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\")", "is_min) if self._input_field: l, r, b, t = self.inner_borders w = width -", "= {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self._is_field_active =", "menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu =", "skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None if icon_id: x, y,", "item_id) item = self._items[item_id] if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id)", "index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id)", "if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x, y", "False self._field_tint = new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id is not", "= True self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items =", "update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] =", "= item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if", "self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y, 0, 0) x,", "height - b - t size = (w, h) self._input_field.set_size(size, includes_borders, is_min) return", "self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index", "item_id, item_text, item_command=None, index=None, persistent=False, update=False, select_initial=True): item = self._popup_menu.add(item_id, item_text, item_command, index=index)", "x, y = self.get_pos(ref_node=self._ref_node) offset_x, offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x,", "and self._selected_item_id not in self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index,", "= self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip = True self._items =", "set_item_text(self, item_id, text): if item_id not in self._item_ids: return self._item_texts[item_id] = text if", "self._selected_item_id != item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id", "y = self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img,", "del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index = self._item_ids.index(item_id) size = len(self._item_ids) self._item_ids.remove(item_id)", "parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image,", "def __card_update_task(self): if self.is_hidden(): return image = self.get_image(composed=False) if not image: return parent", "is_min=True) def destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not None and", "def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts", "text): if item_id not in self._item_ids: return self._item_texts[item_id] = text if item_id in", "= [] self._selected_item_id = None self._selection_handlers = {} self._is_field_active = False self._field_back_img =", "None if icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h,", "text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text + (\": \" + text if text", "h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task", "self.inner_borders w, h = self.min_size w = field_width + l + r size", "if not parent: return x, y = self.get_pos() w, h = self.get_size() img", "def set_item_text(self, item_id, text): if item_id not in self._item_ids: return self._item_texts[item_id] = text", "0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l,", "draw_field=False) image.blend_sub_image(img, 0, 0, 0, 0) return image def add_item(self, item_id, item_text, item_command=None,", "== text: return False self._field_text = text if self._field_text_in_tooltip and self.tooltip_text: self.override_tooltip_text(self.tooltip_text +", "input_field(self): return self._input_field @input_field.setter def input_field(self, input_field): self._input_field = input_field if not self.sizer:", "self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in self._persistent_items or", "None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy()", "= Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field", "self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def __on_hide(self):", "is not None and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear()", "h) self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0.,", "self.get_image(composed=False) if not image: return parent = self.parent if not parent: return x,", "tint if tint else Skin.colors[\"combobox_field_tint_default\"] if self._field_tint == new_tint: return False self._field_tint =", "<filename>src/gui/combobox.py<gh_stars>10-100 from .base import * from .button import Button from .menu import Menu", "self._selected_item_id == item_id: self._selected_item_id = None if index == size - 1: index", "!= show: return False r = field.show() if show else field.hide() self.__update_card_image() return", "self.widget_type = \"combobox\" self.command = self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip", "self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id) update = True if update: self._popup_menu.update() def set_size(self,", "from .menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width,", "self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if item_id not", "0, 0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed():", "x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self, state,", "not None def set_field_back_image(self, image): self._field_back_img = image def __get_image(self, state=None, draw_field=True): width,", "else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id = None if index == size", "item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field @input_field.setter def input_field(self,", "field = self._input_field if not field or field.is_hidden() != show: return False r", "self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide) l, r, b, t =", "== new_tint: return False self._field_tint = new_tint self.__update_card_image() return True def select_none(self): if", "text self._field_text_in_tooltip = True self._items = {} self._item_ids = [] self._item_texts = {}", "__update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id,", "self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self,", "- l - r h = height - b - t size =", "set_item_index(self, item_id, index): if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item", "r def is_input_field_hidden(self): field = self._input_field if not field or field.is_hidden(): return True", "= self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index, update=True) self._selected_item_id = None self.set_text(\"\") def select_item(self, item_id): if", "gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type = \"combobox\" self.command =", "self._persistent_items: index = self._item_ids.index(self._selected_item_id) selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id", "0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu = Menu(on_hide=self.__on_hide)", "return r def is_input_field_hidden(self): field = self._input_field if not field or field.is_hidden(): return", "img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self,", "0, x, y, w, h) self._combo_icon = img self._combo_icon_disabled = icon_disabled = PNMImage(img)", "in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu = None def", "def __on_select(self, item_id): if self._selected_item_id == item_id: return update = False if self._selected_item_id", "select_item(self, item_id): if item_id not in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id", "ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self,", "and sel_item_id not in self._persistent_items: self._items[self._selected_item_id].destroy() self._input_field = None self._items.clear() self._selection_handlers.clear() self._popup_menu.destroy() self._popup_menu", "id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint = tint if tint else", "field_width + l + r size = (w, h) self.set_size(size, is_min=True) def destroy(self):", "b, t = self.inner_borders w, h = self.min_size w = field_width + l", "return False r = field.show() if show else field.hide() self.__update_card_image() return r def", "= lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] =", "icon_disabled = PNMImage(img) icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon", "== item_id: return update = False if self._selected_item_id is not None and self._selected_item_id", "if select_initial and len(self._items) == 1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id", "r, b, t = self.inner_borders w, h = self.min_size w = field_width +", "def show_input_field(self, show=True): field = self._input_field if not field or field.is_hidden() != show:", "= parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0, x, y, w, h) img.blend_sub_image(image, 0,", "= {} self._item_ids = [] self._item_texts = {} self._persistent_items = [] self._selected_item_id =", "else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items)", "= self._field_back_img * self._field_tint if self._field_label: x, y = self.get_field_label_offset() field_back_img.blend_sub_image(self._field_label, x, y,", "not parent: return x, y = self.get_pos() w, h = self.get_size() img =", "= input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer =", "self._selected_item_id == item_id: return update = False if self._selected_item_id is not None and", "composed=False) image.blend_sub_image(img, 0, 0, 0, 0) if self._combo_icon: x, y = self.get_icon_offset() image.blend_sub_image(self._combo_icon,", "batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint = tint if tint else Skin.colors[\"combobox_field_tint_default\"]", "= self.get_field_offset() image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0,", "self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self, text): if self._field_text ==", "if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent:", "!= item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self): return self._input_field @input_field.setter def", "self._field_label = font.create_image(text, color) else: self._field_label = None if icon_id: x, y, w,", "def __on_hide(self): if self.active: self.active = False self.on_leave(force=True) def __show_menu(self): if not self._popup_menu.items:", "h = self.get_size() img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img:", "self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task()", "True self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items = []", "is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id) if", "self._popup_menu def clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = []", "Button from .menu import Menu class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent,", "self._input_field = input_field if not self.sizer: sizer = Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer", "self._item_texts = {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self._is_field_active", "__init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text) self.widget_type =", "new_tint: return False self._field_tint = new_tint self.__update_card_image() return True def select_none(self): if self._selected_item_id", "in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu):", "!= item_id: self._popup_menu.set_item_text(item_id, text, update=True) else: item = self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id ==", "image def get_image(self, state=None, composed=False): field = self._input_field if not field or field.is_hidden(check_ancestors=False):", "self._persistent_items = [] self._selected_item_id = None self._selection_handlers = {} self.set_text(\"\") def __card_update_task(self): if", "class ComboBox(Button): _ref_node = NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"):", "self.command = self.__show_menu self._field_width = field_width self._field_text = text self._field_text_in_tooltip = True self._items", "-= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled = None self._popup_menu", "= (x + offset_x, y + offset_y) offset_x, offset_y = self.get_menu_offset(\"top\") w, h", "__on_select(self, item_id): if self._selected_item_id == item_id: return update = False if self._selected_item_id is", "x, y, w, h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0,", "item_id): if self._selected_item_id == item_id: return update = False if self._selected_item_id is not", "item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if item_id not in self._item_ids:", "item_id, index): if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item =", "show_input_field(self, show=True): field = self._input_field if not field or field.is_hidden() != show: return", "else field.hide() self.__update_card_image() return r def is_input_field_hidden(self): field = self._input_field if not field", "self._selected_item_id def get_item_ids(self): return self._item_ids def allow_field_text_in_tooltip(self, allow=True): self._field_text_in_tooltip = allow def set_text(self,", "offset_y = self.get_menu_offset(\"bottom\") pos = (x + offset_x, y + offset_y) offset_x, offset_y", "Sizer(\"horizontal\") sizer.default_size = self.min_size self.sizer = sizer self.sizer.add(input_field) def show_input_field(self, show=True): field =", "height def has_icon(self): return self._combo_icon is not None def set_field_back_image(self, image): self._field_back_img =", "h = Skin.atlas.regions[icon_id] img = PNMImage(w, h, 4) img.copy_sub_image(Skin.atlas.image, 0, 0, x, y,", "1: if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def", "if update: self._popup_menu.update() def remove_item(self, item_id): if item_id not in self._item_ids: return item", "= skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None", "= False if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index", "self._items[self._selected_item_id] item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not", "in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index, update=True) @property def input_field(self):", "not field or field.is_hidden() != show: return False r = field.show() if show", "self._items = {} self._item_ids = [] self._item_texts = {} self._persistent_items = [] self._selected_item_id", "skin_text[\"font\"] color = skin_text[\"color\"] self._field_label = font.create_image(text, color) else: self._field_label = None self.__update_card_image()", "1: index -= 1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id", "update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if self._selected_item_id not in self._persistent_items: self._popup_menu.remove(self._selected_item_id)", "self.override_tooltip_text(self.tooltip_text + (\": \" + text if text else \"\")) if text: skin_text", "self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if", "NodePath(\"combobox_ref_node\") def __init__(self, parent, field_width, gfx_ids, text=\"\", icon_id=\"\", tooltip_text=\"\"): Button.__init__(self, parent, gfx_ids, tooltip_text=tooltip_text)", "= item_text if persistent: self._persistent_items.append(item_id) if select_initial and len(self._items) == 1: if not", "x, y, 0, 0) return image def get_image(self, state=None, composed=False): field = self._input_field", "in self._item_ids: return self._selection_handlers[item_id]() def get_selected_item(self): return self._selected_item_id def get_item_ids(self): return self._item_ids def", "= self._popup_menu.add(item_id, item_text, item_command, index=index) self._items[item_id] = item self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if", "selected_item = self._items[self._selected_item_id] self._popup_menu.add_item(selected_item, index) update = True self._selected_item_id = item_id self.set_text(self._item_texts[item_id]) if", "index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id] = item_text if persistent: self._persistent_items.append(item_id)", "item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if", "1 if index >= 0: self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id)", "task = self.__card_update_task if self.is_card_update_delayed(): task_id = \"update_card_image\" PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\")", "self._item_ids: return item = self._items[item_id] del self._items[item_id] del self._item_texts[item_id] del self._selection_handlers[item_id] index =", "= self._items[item_id] if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id) self._popup_menu.add_item(item, index,", "PendingTasks.add(task, task_id, sort=1, id_prefix=self.widget_id, batch_id=\"widget_card_update\") else: task() def set_field_tint(self, tint=None): new_tint = tint", "y = self.get_icon_offset() image.blend_sub_image(self._combo_icon, x, y, 0, 0) return image def get_image(self, state=None,", "clear(self): self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts =", "= self.inner_borders w, h = self.min_size w = field_width + l + r", "0, 0, x, y, w, h) img.blend_sub_image(image, 0, 0, 0, 0) self.card.copy_sub_image(self, img,", "self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self, item_id): if item_id not", "destroy(self): Button.destroy(self) sel_item_id = self._selected_item_id if sel_item_id is not None and sel_item_id not", "if item_id not in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if", "self.select_item(self._item_ids[index]) else: self.set_text(\"\") if item_id in self._persistent_items: self._persistent_items.remove(item_id) def update_popup_menu(self): self._popup_menu.update() def create_popup_menu(self):", "field.is_hidden() != show: return False r = field.show() if show else field.hide() self.__update_card_image()", "def __show_menu(self): if not self._popup_menu.items: return self.active = True x, y = self.get_pos(ref_node=self._ref_node)", "return x, y = self.get_pos() w, h = self.get_size() img = PNMImage(w, h,", "def select_none(self): if self._selected_item_id is not None and self._selected_item_id not in self._persistent_items: index", "self._popup_menu.destroy() self._popup_menu = Menu(on_hide=self.__on_hide) self._items = {} self._item_ids = [] self._item_texts = {}", "b, t = self.inner_borders w = width - l - r h =", "create_popup_menu(self): return Menu(on_hide=self.__on_hide) def set_popup_menu(self, menu): self._popup_menu = menu def get_popup_menu(self): return self._popup_menu", "0) self.card.copy_sub_image(self, img, w, h) def __update_card_image(self): task = self.__card_update_task if self.is_card_update_delayed(): task_id", "update: self._popup_menu.update() def remove_item(self, item_id): if item_id not in self._item_ids: return item =", "self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not in self._item_ids:", "self._selection_handlers[item_id] = lambda: self.__on_select(item_id) if index is None: self._item_ids.append(item_id) else: self._item_ids.insert(index, item_id) self._item_texts[item_id]", "if not persistent: self._popup_menu.remove(item_id) self._selected_item_id = item_id self.set_text(item_text) if update: self._popup_menu.update() def remove_item(self,", "!= item_id: self._popup_menu.remove(item_id, update=True, destroy=True) else: item.destroy() if self._selected_item_id == item_id: self._selected_item_id =", "in self._item_ids: return self._item_ids.remove(item_id) self._item_ids.insert(index, item_id) item = self._items[item_id] if item_id in self._persistent_items", "sizer self.sizer.add(input_field) def show_input_field(self, show=True): field = self._input_field if not field or field.is_hidden()", "len(self._item_ids) self._item_ids.remove(item_id) if item_id in self._persistent_items or self._selected_item_id != item_id: self._popup_menu.remove(item_id, update=True, destroy=True)", "else: self._field_label = None if icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img", "self._field_label = None if icon_id: x, y, w, h = Skin.atlas.regions[icon_id] img =", "PNMImage(width, height, 4) if draw_field: field_back_img = self._field_back_img * self._field_tint if self._field_label: x,", "[] self._selected_item_id = None self._selection_handlers = {} self._is_field_active = False self._field_back_img = None", "0) x, y = self.get_field_offset() image.blend_sub_image(field_back_img, x, y, 0, 0) img = Button.get_image(self,", "img = PNMImage(w, h, 4) parent_img = parent.get_image(composed=False) if parent_img: img.copy_sub_image(parent_img, 0, 0,", "self._field_tint == new_tint: return False self._field_tint = new_tint self.__update_card_image() return True def select_none(self):", "item.set_text(text) if self._selected_item_id == item_id: self.set_text(text) def get_item_text(self, item_id): if item_id not in", "= [] self._item_texts = {} self._persistent_items = [] self._selected_item_id = None self._selection_handlers =", "not in self._item_ids: return return self._item_texts[item_id] def set_item_index(self, item_id, index): if item_id not", "h = self.min_size w = field_width + l + r size = (w,", "item_id): if item_id not in self._item_ids: return item = self._items[item_id] del self._items[item_id] del", "= field_width self._field_text = text self._field_text_in_tooltip = True self._items = {} self._item_ids =", "image.copy_sub_image(field_img, x, y, 0, 0) img = self.__get_image(state, draw_field=False) image.blend_sub_image(img, 0, 0, 0,", "icon_disabled.make_grayscale() icon_disabled -= LColorf(0., 0., 0., .25) icon_disabled.make_rgb() else: self._combo_icon = self._combo_icon_disabled =" ]
[ "= id self.info = info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" %", "phone=None): self.f_name = f_name self.l_name = l_name self.company = company self.id = id", "self.id = id self.info = info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\"", "company self.id = id self.info = info self.phone = phone def __repr__(self): return", "or other.id is None or self.id == other.id) and self.info == other.info def", "f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name = l_name self.company", "other): return (self.id is None or other.id is None or self.id == other.id)", "% (self.id, self.info, self.f_name, self.company) def __eq__(self, other): return (self.id is None or", "= company self.id = id self.info = info self.phone = phone def __repr__(self):", "def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name =", "\"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self, other): return (self.id is None", "f_name self.l_name = l_name self.company = company self.id = id self.info = info", "phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self, other):", "= l_name self.company = company self.id = id self.info = info self.phone =", "and self.info == other.info def id_or_max(self): if self.id: return int(self.id) else: return maxsize", "id self.info = info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id,", "= info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name,", "(self.id is None or other.id is None or self.id == other.id) and self.info", "class Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name", "self.f_name = f_name self.l_name = l_name self.company = company self.id = id self.info", "self.company = company self.id = id self.info = info self.phone = phone def", "other.id) and self.info == other.info def id_or_max(self): if self.id: return int(self.id) else: return", "l_name self.company = company self.id = id self.info = info self.phone = phone", "return (self.id is None or other.id is None or self.id == other.id) and", "self.id == other.id) and self.info == other.info def id_or_max(self): if self.id: return int(self.id)", "__init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name = l_name", "self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def", "self.info, self.f_name, self.company) def __eq__(self, other): return (self.id is None or other.id is", "(self.id, self.info, self.f_name, self.company) def __eq__(self, other): return (self.id is None or other.id", "__repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self, other): return (self.id", "sys import maxsize class Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None):", "def __eq__(self, other): return (self.id is None or other.id is None or self.id", "maxsize class Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name =", "from sys import maxsize class Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None,", "info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company)", "self.company) def __eq__(self, other): return (self.id is None or other.id is None or", "id=None, info=None, phone=None): self.f_name = f_name self.l_name = l_name self.company = company self.id", "Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name", "def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self, other): return", "self.info = info self.phone = phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info,", "return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self, other): return (self.id is", "None or other.id is None or self.id == other.id) and self.info == other.info", "info=None, phone=None): self.f_name = f_name self.l_name = l_name self.company = company self.id =", "= phone def __repr__(self): return \"%s:%s;%s;%s\" % (self.id, self.info, self.f_name, self.company) def __eq__(self,", "other.id is None or self.id == other.id) and self.info == other.info def id_or_max(self):", "is None or other.id is None or self.id == other.id) and self.info ==", "None or self.id == other.id) and self.info == other.info def id_or_max(self): if self.id:", "== other.id) and self.info == other.info def id_or_max(self): if self.id: return int(self.id) else:", "import maxsize class Contact: def __init__(self, f_name=None, l_name=None, company=None, id=None, info=None, phone=None): self.f_name", "company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name = l_name self.company = company", "__eq__(self, other): return (self.id is None or other.id is None or self.id ==", "is None or self.id == other.id) and self.info == other.info def id_or_max(self): if", "or self.id == other.id) and self.info == other.info def id_or_max(self): if self.id: return", "self.f_name, self.company) def __eq__(self, other): return (self.id is None or other.id is None", "self.l_name = l_name self.company = company self.id = id self.info = info self.phone", "l_name=None, company=None, id=None, info=None, phone=None): self.f_name = f_name self.l_name = l_name self.company =", "= f_name self.l_name = l_name self.company = company self.id = id self.info =" ]
[ "import argparse from .env_viewer import viewer from .envs.bm_config import BM_Config if __name__ ==", "test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser) args = parser.parse_args() bm_config.change_bm_config(args)", "(default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser) args = parser.parse_args() bm_config.change_bm_config(args) viewer(args.env)", "to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser) args = parser.parse_args()", "help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser) args =", "Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser", "import BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env',", "= argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config", "parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)')", "Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser =", "if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment", "\"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default:", "Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config()", "== \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test", "parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser)", ".env_viewer import viewer from .envs.bm_config import BM_Config if __name__ == \"__main__\": parser =", "viewer from .envs.bm_config import BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym", "__name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to", "BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1',", "argparse from .env_viewer import viewer from .envs.bm_config import BM_Config if __name__ == \"__main__\":", "default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config = BM_Config() parser = bm_config.add_bm_args(parser) args", "from .env_viewer import viewer from .envs.bm_config import BM_Config if __name__ == \"__main__\": parser", ".envs.bm_config import BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer')", "import viewer from .envs.bm_config import BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive", "from .envs.bm_config import BM_Config if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Assistive Gym Environment", "argparse.ArgumentParser(description='Assistive Gym Environment Viewer') parser.add_argument('--env', default='ScratchItchJaco-v1', help='Environment to test (default: ScratchItchJaco-v1)') bm_config =" ]
[ "far : \" + str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page)", "str(user_id)) followers = [] friends = [] max_followers = 100000 max_friends = 100000", "max_friends: break print(\"Friends so far : \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError", "network for user with id \" + str(user_id)) followers = [] friends =", "return statuses def get_user_network(user_id): print(\"Searching network for user with id \" + str(user_id))", "tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 return user_json def", ">= max_friends: break print(\"Friends so far : \" + str(len(friends))) print(\"finished friends\") except", "+ str(user_id)) followers = [] friends = [] max_followers = 100000 max_friends =", "# followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print (\"This user", "# Aristotle University's Twitter user ID user_id = \"234343780\" # <NAME>'s user_id #user_id", "https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count)", "compression=True) def get_user(user_id): print(\"Searching full information for user with id \" + str(user_id))", "0 return user_json def get_user_tweets(user_id): timeline = [] progress = 0 statuses =", "def get_user(user_id): print(\"Searching full information for user with id \" + str(user_id)) try:", "0 print(\"User with ID: \" + user_id + \" has \" + str(len(followers))", "print (\"This user has \"+friends_count+\" friends\") #### Get the network (friends, followers) of", "user_id #user_id = \"50374439\" ### Get the entire timeline of tweets and retweets", "the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count =", "has \" + str(len(followers)) + \" followers and \" + str(len(friends)) + \"", "tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching", "user has \"+friends_count+\" friends\") #### Get the network (friends, followers) of the user", "\"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key,", "user with id \" + str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as", "str(len(friends)) + \" friends\") custom_object = { \"id\": user_id, \"followers\": followers, \"friends\": friends", "(\"This user has \"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\" friends\") ####", "as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 print(\"User with", "friends\") #### Get the network (friends, followers) of the user ### # network", "has the screen name: \"+screen_name) # print (\"This user has \"+followers_count+\" followers\") #", "# Initialize the API consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret", "= \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using the keys auth =", "# print (\"This user has \"+friends_count+\" friends\") #### Get the network (friends, followers)", "followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print (\"This user has", "all timeline items\") return statuses def get_user_network(user_id): print(\"Searching network for user with id", "entire timeline of tweets and retweets of a user ### statuses = get_user_tweets(user_id)", ": \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with code", "get_user_tweets(user_id): timeline = [] progress = 0 statuses = [] for status in", "status in statuses: print (status._json[\"text\"]) #### Get full information about the user ###", "except tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0", "### # user_json = get_user(user_id) # Access all the information using .*field* #", "user has \"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\" friends\") #### Get", "the user ### # user_json = get_user(user_id) # Access all the information using", "= \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate", "progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\") return statuses def get_user_network(user_id): print(\"Searching", "has \"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\" friends\") #### Get the", "\"friends\": friends } return custom_object if __name__ == '__main__': # Aristotle University's Twitter", "\"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\" friends\") #### Get the network", "str(len(followers)) + \" followers and \" + str(len(friends)) + \" friends\") custom_object =", "#### Get full information about the user ### # user_json = get_user(user_id) #", "str(tweep_error.response.text)) return 0 print(\"User with ID: \" + user_id + \" has \"", "if __name__ == '__main__': # Aristotle University's Twitter user ID user_id = \"234343780\"", "max_followers = 100000 max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page)", "print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text))", "about the user ### # user_json = get_user(user_id) # Access all the information", "full information for user with id \" + str(user_id)) try: user_json = api.get_user(user_id)", "far : \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with", "str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print (\"This user has the screen", "= 100000 max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if", "Twitter user ID user_id = \"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ###", "user with id \" + str(user_id)) followers = [] friends = [] max_followers", "user ### statuses = get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) #### Get", "+ str(len(followers)) + \" followers and \" + str(len(friends)) + \" friends\") custom_object", "\" + str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends)", "using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) #", "print(\"Searching network for user with id \" + str(user_id)) followers = [] friends", "\" + str(user_id)) followers = [] friends = [] max_followers = 100000 max_friends", "with id \" + str(user_id)) followers = [] friends = [] max_followers =", "wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for user with id \"", "progress = 0 statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1", "import pymongo #from src_python import utilities # Initialize the API consumer keys and", "followers = [] friends = [] max_followers = 100000 max_friends = 100000 try:", "(\"This user has the screen name: \"+screen_name) # print (\"This user has \"+followers_count+\"", "{ \"id\": user_id, \"followers\": followers, \"friends\": friends } return custom_object if __name__ ==", "network (friends, followers) of the user ### # network = get_user_network(user_id) # print(network[\"friends\"])", "timeline items\") return statuses def get_user_network(user_id): print(\"Searching network for user with id \"", "get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) #### Get full information about the", "\"+friends_count+\" friends\") #### Get the network (friends, followers) of the user ### #", "tweepy import json import pymongo #from src_python import utilities # Initialize the API", "= { \"id\": user_id, \"followers\": followers, \"friends\": friends } return custom_object if __name__", "of tweets and retweets of a user ### statuses = get_user_tweets(user_id) for status", "id \" + str(user_id)) followers = [] friends = [] max_followers = 100000", "with id \" + str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error:", "print(\"Error with code : \" + str(tweep_error.response.text)) return 0 print(\"User with ID: \"", "= \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using the", ": \" + str(tweep_error.response.text)) return 0 print(\"User with ID: \" + user_id +", "custom_object = { \"id\": user_id, \"followers\": followers, \"friends\": friends } return custom_object if", "__name__ == '__main__': # Aristotle University's Twitter user ID user_id = \"234343780\" #", "\" followers and \" + str(len(friends)) + \" friends\") custom_object = { \"id\":", "user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code : \" +", "Get full information about the user ### # user_json = get_user(user_id) # Access", "print (\"This user has \"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\" friends\")", "return custom_object if __name__ == '__main__': # Aristotle University's Twitter user ID user_id", "\" + str(len(friends)) + \" friends\") custom_object = { \"id\": user_id, \"followers\": followers,", "# # print (\"This user has the screen name: \"+screen_name) # print (\"This", "a user ### statuses = get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) ####", "id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\") return statuses def", "page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so far", "return 0 print(\"User with ID: \" + user_id + \" has \" +", "print(\"Followers so far : \" + str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids,", "\" friends\") custom_object = { \"id\": user_id, \"followers\": followers, \"friends\": friends } return", "+ \" has \" + str(len(followers)) + \" followers and \" + str(len(friends))", "tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for user with id", "get_user(user_id): print(\"Searching full information for user with id \" + str(user_id)) try: user_json", "import json import pymongo #from src_python import utilities # Initialize the API consumer", "Get the entire timeline of tweets and retweets of a user ### statuses", ": \" + str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if", "information for user with id \" + str(user_id)) try: user_json = api.get_user(user_id) except", "= get_user(user_id) # Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name", "all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count", "def get_user_network(user_id): print(\"Searching network for user with id \" + str(user_id)) followers =", "src_python import utilities # Initialize the API consumer keys and access tokens consumer_key", "\" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with code :", "friends_count = str(user_json.friends_count) # # print (\"This user has the screen name: \"+screen_name)", "statuses def get_user_network(user_id): print(\"Searching network for user with id \" + str(user_id)) followers", "followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so far : \" + str(len(followers)))", "consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token =", "try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers", "#### Get the network (friends, followers) of the user ### # network =", "page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so far", "keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)", "for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so", "and \" + str(len(friends)) + \" friends\") custom_object = { \"id\": user_id, \"followers\":", "tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\"", "+ str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code", "ID user_id = \"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ### Get the", "max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >=", "custom_object if __name__ == '__main__': # Aristotle University's Twitter user ID user_id =", "user_id = \"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ### Get the entire", "\"+screen_name) # print (\"This user has \"+followers_count+\" followers\") # print (\"This user has", "str(user_json.friends_count) # # print (\"This user has the screen name: \"+screen_name) # print", "\" + str(tweep_error.response.text)) return 0 print(\"User with ID: \" + user_id + \"", "has \"+friends_count+\" friends\") #### Get the network (friends, followers) of the user ###", "of all timeline items\") return statuses def get_user_network(user_id): print(\"Searching network for user with", "consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full", "user has the screen name: \"+screen_name) # print (\"This user has \"+followers_count+\" followers\")", "friends = [] max_followers = 100000 max_friends = 100000 try: for page in", "\" + str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline = [] progress", "Aristotle University's Twitter user ID user_id = \"234343780\" # <NAME>'s user_id #user_id =", "so far : \" + str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages():", "# print (\"This user has \"+followers_count+\" followers\") # print (\"This user has \"+friends_count+\"", "100000 max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers)", "statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out", "\"followers\": followers, \"friends\": friends } return custom_object if __name__ == '__main__': # Aristotle", "str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline = [] progress = 0", "consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" #", "\"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using the keys", "### statuses = get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) #### Get full", "id \" + str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error", "\" + str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with", "of a user ### statuses = get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"])", "\" has \" + str(len(followers)) + \" followers and \" + str(len(friends)) +", "== '__main__': # Aristotle University's Twitter user ID user_id = \"234343780\" # <NAME>'s", "friends } return custom_object if __name__ == '__main__': # Aristotle University's Twitter user", "the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True,", "followers, \"friends\": friends } return custom_object if __name__ == '__main__': # Aristotle University's", "# screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) #", "= get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) #### Get full information about", "### Get the entire timeline of tweets and retweets of a user ###", "try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code : \"", "str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print (\"This", "timeline of tweets and retweets of a user ### statuses = get_user_tweets(user_id) for", "auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def", "get_user_network(user_id): print(\"Searching network for user with id \" + str(user_id)) followers = []", "tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 return", ">= max_followers: break print(\"Followers so far : \" + str(len(followers))) print(\"finished followers\") for", "for user with id \" + str(user_id)) followers = [] friends = []", "# https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count =", "print(\"Friends so far : \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error:", "so far : \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error", "keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\"", "(status._json[\"text\"]) #### Get full information about the user ### # user_json = get_user(user_id)", "Get the network (friends, followers) of the user ### # network = get_user_network(user_id)", "+ \" friends\") custom_object = { \"id\": user_id, \"followers\": followers, \"friends\": friends }", "API consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token", "break print(\"Followers so far : \" + str(len(followers))) print(\"finished followers\") for page in", "tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth,", "+ str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >=", "= \"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ### Get the entire timeline", "break print(\"Friends so far : \" + str(len(friends))) print(\"finished friends\") except tweepy.TweepError as", "= str(user_json.friends_count) # # print (\"This user has the screen name: \"+screen_name) #", "id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so far : \" +", "with code : \" + str(tweep_error.response.text)) return 0 print(\"User with ID: \" +", "timeline = [] progress = 0 statuses = [] for status in tweepy.Cursor(api.user_timeline,", "tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so far : \"", ": \" + str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline = []", "as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 return user_json", "\"+str(progress)+\" out of all timeline items\") return statuses def get_user_network(user_id): print(\"Searching network for", "print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break", "\"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ### Get the entire timeline of", "with ID: \" + user_id + \" has \" + str(len(followers)) + \"", "for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline", "user_id, \"followers\": followers, \"friends\": friends } return custom_object if __name__ == '__main__': #", "friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so far : \" + str(len(friends)))", "+ str(len(friends)) + \" friends\") custom_object = { \"id\": user_id, \"followers\": followers, \"friends\":", "= str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print (\"This user has the", "= tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id):", "ID: \" + user_id + \" has \" + str(len(followers)) + \" followers", "str(len(followers))) print(\"finished followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends:", "#from src_python import utilities # Initialize the API consumer keys and access tokens", "information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count)", "\"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy", "return 0 return user_json def get_user_tweets(user_id): timeline = [] progress = 0 statuses", "followers and \" + str(len(friends)) + \" friends\") custom_object = { \"id\": user_id,", "for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so", "[] friends = [] max_followers = 100000 max_friends = 100000 try: for page", "(\"This user has \"+friends_count+\" friends\") #### Get the network (friends, followers) of the", "json import pymongo #from src_python import utilities # Initialize the API consumer keys", "+ user_id + \" has \" + str(len(followers)) + \" followers and \"", "for status in statuses: print (status._json[\"text\"]) #### Get full information about the user", "\"<KEY>\" # Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret)", "print(\"Searching full information for user with id \" + str(user_id)) try: user_json =", "= tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for user with", "print (\"This user has the screen name: \"+screen_name) # print (\"This user has", "followers\") for page in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends", "= [] max_followers = 100000 max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids,", "tweets and retweets of a user ### statuses = get_user_tweets(user_id) for status in", "'__main__': # Aristotle University's Twitter user ID user_id = \"234343780\" # <NAME>'s user_id", "for user with id \" + str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError", "= 0 statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched", "code : \" + str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline =", "status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\")", "tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 print(\"User", "<NAME>'s user_id #user_id = \"50374439\" ### Get the entire timeline of tweets and", "[] progress = 0 statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status)", "retweets of a user ### statuses = get_user_tweets(user_id) for status in statuses: print", "str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with code : \" +", "# Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name)", "timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\") return statuses def get_user_network(user_id):", "access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using the keys auth", "with code : \" + str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline", "and retweets of a user ### statuses = get_user_tweets(user_id) for status in statuses:", "\"id\": user_id, \"followers\": followers, \"friends\": friends } return custom_object if __name__ == '__main__':", "wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for user with id \" +", "0 statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\"", "# <NAME>'s user_id #user_id = \"50374439\" ### Get the entire timeline of tweets", "= \"50374439\" ### Get the entire timeline of tweets and retweets of a", "using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True,", "import tweepy import json import pymongo #from src_python import utilities # Initialize the", "followers\") # print (\"This user has \"+friends_count+\" friends\") #### Get the network (friends,", "in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so far :", "tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\") return statuses", "len(followers) >= max_followers: break print(\"Followers so far : \" + str(len(followers))) print(\"finished followers\")", "and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret", "= [] progress = 0 statuses = [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items():", "# user_json = get_user(user_id) # Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object", "+ \" followers and \" + str(len(friends)) + \" friends\") custom_object = {", "user ### # user_json = get_user(user_id) # Access all the information using .*field*", "statuses: print (status._json[\"text\"]) #### Get full information about the user ### # user_json", "user_id + \" has \" + str(len(followers)) + \" followers and \" +", "#user_id = \"50374439\" ### Get the entire timeline of tweets and retweets of", "the screen name: \"+screen_name) # print (\"This user has \"+followers_count+\" followers\") # print", "friends\") except tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return", "information about the user ### # user_json = get_user(user_id) # Access all the", "Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api =", "statuses = get_user_tweets(user_id) for status in statuses: print (status._json[\"text\"]) #### Get full information", "[] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all", "name: \"+screen_name) # print (\"This user has \"+followers_count+\" followers\") # print (\"This user", "utilities # Initialize the API consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\"", "= api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text))", "tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return 0 print(\"User with ID:", "\"50374439\" ### Get the entire timeline of tweets and retweets of a user", "code : \" + str(tweep_error.response.text)) return 0 print(\"User with ID: \" + user_id", "= \"<KEY>\" # Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token,", "= [] friends = [] max_followers = 100000 max_friends = 100000 try: for", "items\") return statuses def get_user_network(user_id): print(\"Searching network for user with id \" +", "access_token_secret = \"<KEY>\" # Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret)", "screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) # #", "def get_user_tweets(user_id): timeline = [] progress = 0 statuses = [] for status", "Initialize the API consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret =", "# print (\"This user has the screen name: \"+screen_name) # print (\"This user", "the entire timeline of tweets and retweets of a user ### statuses =", "followers) of the user ### # network = get_user_network(user_id) # print(network[\"friends\"]) # print(network[\"followers\"])", "in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of all timeline items\") return", "the network (friends, followers) of the user ### # network = get_user_network(user_id) #", "= [] for status in tweepy.Cursor(api.user_timeline, id=user_id).items(): timeline.append(status) progress+=1 print(\"Fetched \"+str(progress)+\" out of", "access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for", "max_followers: break print(\"Followers so far : \" + str(len(followers))) print(\"finished followers\") for page", "screen name: \"+screen_name) # print (\"This user has \"+followers_count+\" followers\") # print (\"This", "# friends_count = str(user_json.friends_count) # # print (\"This user has the screen name:", "if len(followers) >= max_followers: break print(\"Followers so far : \" + str(len(followers))) print(\"finished", "id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so far : \" +", "} return custom_object if __name__ == '__main__': # Aristotle University's Twitter user ID", "user ID user_id = \"234343780\" # <NAME>'s user_id #user_id = \"50374439\" ### Get", "friends\") custom_object = { \"id\": user_id, \"followers\": followers, \"friends\": friends } return custom_object", "[] max_followers = 100000 max_friends = 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages():", "100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break", "\" + str(len(followers)) + \" followers and \" + str(len(friends)) + \" friends\")", "user_json = get_user(user_id) # Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object #", "+ str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id): timeline = [] progress =", "in statuses: print (status._json[\"text\"]) #### Get full information about the user ### #", "auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information", "len(friends) >= max_friends: break print(\"Friends so far : \" + str(len(friends))) print(\"finished friends\")", "api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code : \" + str(tweep_error.response.text)) return", "print(\"Error with code : \" + str(tweep_error.response.text)) return 0 return user_json def get_user_tweets(user_id):", ".*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count", "= 100000 try: for page in tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers:", "user_json def get_user_tweets(user_id): timeline = [] progress = 0 statuses = [] for", "get_user(user_id) # Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name =", "= str(user_json.screen_name) # followers_count = str(user_json.followers_count) # friends_count = str(user_json.friends_count) # # print", "Access all the information using .*field* # https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object # screen_name = str(user_json.screen_name) #", "the API consumer keys and access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\"", "pymongo #from src_python import utilities # Initialize the API consumer keys and access", "+ str(tweep_error.response.text)) return 0 print(\"User with ID: \" + user_id + \" has", "tweepy.Cursor(api.followers_ids, id=user_id).pages(): followers.extend(page) if len(followers) >= max_followers: break print(\"Followers so far : \"", "\" + user_id + \" has \" + str(len(followers)) + \" followers and", "print (status._json[\"text\"]) #### Get full information about the user ### # user_json =", "api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) def get_user(user_id): print(\"Searching full information for user", "in tweepy.Cursor(api.friends_ids, id=user_id).pages(): friends.extend(page) if len(friends) >= max_friends: break print(\"Friends so far :", "print(\"User with ID: \" + user_id + \" has \" + str(len(followers)) +", "out of all timeline items\") return statuses def get_user_network(user_id): print(\"Searching network for user", "return user_json def get_user_tweets(user_id): timeline = [] progress = 0 statuses = []", "University's Twitter user ID user_id = \"234343780\" # <NAME>'s user_id #user_id = \"50374439\"", "+ str(len(friends))) print(\"finished friends\") except tweepy.TweepError as tweep_error: print(\"Error with code : \"", "if len(friends) >= max_friends: break print(\"Friends so far : \" + str(len(friends))) print(\"finished", "full information about the user ### # user_json = get_user(user_id) # Access all", "# Authenticate tweepy using the keys auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api", "import utilities # Initialize the API consumer keys and access tokens consumer_key =", "access tokens consumer_key = \"LukFsjKDofVcCdiKsCnxiLx2V\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret =", "str(user_id)) try: user_json = api.get_user(user_id) except tweepy.TweepError as tweep_error: print(\"Error with code :", "print(\"Fetched \"+str(progress)+\" out of all timeline items\") return statuses def get_user_network(user_id): print(\"Searching network", "(friends, followers) of the user ### # network = get_user_network(user_id) # print(network[\"friends\"]) #", "consumer_secret = \"<KEY>\" access_token = \"<KEY>\" access_token_secret = \"<KEY>\" # Authenticate tweepy using" ]
[ "= map(int, each_step.split()) if r < edge_r: edge_r = r if c <", "<reponame>EternalTitan/ICPC-Practise def countX(steps): RC_MAXIMUM = 1000000 edge_r = edge_c = RC_MAXIMUM for each_step", "steps: r, c = map(int, each_step.split()) if r < edge_r: edge_r = r", "RC_MAXIMUM = 1000000 edge_r = edge_c = RC_MAXIMUM for each_step in steps: r,", "1000000 edge_r = edge_c = RC_MAXIMUM for each_step in steps: r, c =", "each_step.split()) if r < edge_r: edge_r = r if c < edge_c: edge_c", "edge_r = edge_c = RC_MAXIMUM for each_step in steps: r, c = map(int,", "edge_r: edge_r = r if c < edge_c: edge_c = c return edge_r", "= 1000000 edge_r = edge_c = RC_MAXIMUM for each_step in steps: r, c", "= edge_c = RC_MAXIMUM for each_step in steps: r, c = map(int, each_step.split())", "if r < edge_r: edge_r = r if c < edge_c: edge_c =", "edge_c = RC_MAXIMUM for each_step in steps: r, c = map(int, each_step.split()) if", "map(int, each_step.split()) if r < edge_r: edge_r = r if c < edge_c:", "for each_step in steps: r, c = map(int, each_step.split()) if r < edge_r:", "c = map(int, each_step.split()) if r < edge_r: edge_r = r if c", "edge_r = r if c < edge_c: edge_c = c return edge_r *", "r < edge_r: edge_r = r if c < edge_c: edge_c = c", "countX(steps): RC_MAXIMUM = 1000000 edge_r = edge_c = RC_MAXIMUM for each_step in steps:", "= r if c < edge_c: edge_c = c return edge_r * edge_c", "each_step in steps: r, c = map(int, each_step.split()) if r < edge_r: edge_r", "< edge_r: edge_r = r if c < edge_c: edge_c = c return", "def countX(steps): RC_MAXIMUM = 1000000 edge_r = edge_c = RC_MAXIMUM for each_step in", "RC_MAXIMUM for each_step in steps: r, c = map(int, each_step.split()) if r <", "= RC_MAXIMUM for each_step in steps: r, c = map(int, each_step.split()) if r", "in steps: r, c = map(int, each_step.split()) if r < edge_r: edge_r =", "r, c = map(int, each_step.split()) if r < edge_r: edge_r = r if" ]
[ "c1 = self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] -", "((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self):", "list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] =", "list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin =", "self.data['voltage_end'] = voltage_end row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence", "12]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row,", "self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x", "self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for", "report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\"", "range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row in [3, 6,", "= self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] =", "= self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 =", "col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1 row", "L self.data['K'] = K def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2", "len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y,", "self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci = self.data['ci']", "self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据", "9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for", "= \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J']", "list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J", "self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph =", "print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper ==", "list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env", "% (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J']", "temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] +", "list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in [3, 6, 9, 12]: for", "this file, but should be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1()", "= [] list_temperature = [] list_weight = [] for row in [1, 4,", "RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__ == '__main__': mc = thermology()", "import copy as xlscopy import shutil import os from numpy import sqrt, abs", "7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for", "calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice']", "EOFError: sys.exit(0) if oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break", "1)] = \"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)]", "print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\")", "print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) *", "self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 =", "m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph", "print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) *", "list_temperature = [] list_weight = [] for row in [1, 4, 7]: for", "col = 1 row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2", "#几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice']", "oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") #", "print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y =", "9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col", "list_weight row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row", "self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名", "self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0']", "reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J',", "计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\")", "self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2']", "= self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a']", "#时间 self.data['list_time'] = list_time for row in [2, 5, 8]: for col in", "= float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col))", "list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False)", "\"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data", "sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from", "self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 +", "# 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none", "= xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2 = [] for row", "self.data['list_temperature'] = list_temperature col = 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量", "col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3", "= 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2']", "= ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def", "in [3, 6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature']", "= self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin =", "= input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper != '1' and oper !=", "list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice']", "list_temperature col = 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] =", "self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water)", "= list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1]", "col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] =", "list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001", "list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2", "REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty = {}", "[] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin']", "i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i) # 最终结果", "i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i", "= {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper =", "= 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 *", "for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for", "= list_weight row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice", "except EOFError: sys.exit(0) if oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else:", "= self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0 =", "(list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def calc_data2(self): c1 =", "list_resistance2 for row in [3, 6, 9, 12]: for col in range(1, 9):", "list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)]", "from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class", "else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in [2, 5, 8, 11]:", "5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance", "list_resistance = [] list_temperature = [] list_weight = [] for row in [1,", "resitence = self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water", "for row in [1, 4, 7, 10]: for col in range(1, 9): if", "col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2']", "= self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 =", "oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper != '1' and oper", "+ list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] =", "for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col)))", "but should be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() #", "[] list_resistance2 = [] list_temperature2 = [] for row in [1, 4, 7,", "while True: try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper !=", "self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] =", "''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance", "6, 9, 12]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue", "= [] list_resistance = [] list_temperature = [] list_weight = [] for row", "* m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def", "((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def calc_data2(self): c1 = self.data['c1'] c0", "== '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './'", "ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L", "= self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water =", "for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i) #", "import Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29',", "if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break", "print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x =", "= self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence =", "self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def", "= temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin)", "= Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J", "voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight", "import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ'", "import xlrd # from xlutils.copy import copy as xlscopy import shutil import os", "0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight", "enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']):", "in [2, 5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance']", "14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end =", "= m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L", "self.data['list_resistance2'] = list_resistance2 for row in [3, 6, 9, 12]: for col in", "m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice)", "abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy for i, x_i", "# 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021", "= temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row", "= list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1,", "print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when", "print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary", "import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method", "os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据", "for row in [3, 6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col)))", "oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) #", "[3, 6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] =", "voltage_end row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] =", "range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y", "if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\")", "= 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time']", "测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0)", "+ 101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] =", "isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in", "i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60))", "be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty()", "continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1 row = 13", "= 1 row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row", "col))) self.data['list_time2'] = list_time2 for row in [2, 5, 8, 11]: for col", "= self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2]", "= self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0]", "self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ']", "row in [2, 5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值", "= self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME,", "J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = []", "voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row =", "self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight =", "input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance = []", "temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci", "temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001)", "self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice '''", "= 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature']", "self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env']", "* list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] =", "数据处理\") while True: try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper", "col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2']", "list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end", "self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x = [] list_y = [] for", "= self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env =", "self.data['L'] = L self.data['K'] = K def calc_data2(self): c1 = self.data['c1'] c0 =", "show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end =", "''' def calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2", "存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1.", "list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1", "for row in [1, 4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col)))", "in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] =", "'1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME)", "= float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = []", "self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2']", "= self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end =", "col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row in", "= 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self):", "try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper != '1' and", "__init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data =", "= {} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {} #", "list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] =", "= self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph", "in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ", "list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence", "# 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running", "= c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] =", "list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice", "elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME)", "self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice", "numpy import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting", "in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row in [2,", "c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i", "print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return", "self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) '''", "list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i])", "import shutil import os from numpy import sqrt, abs import sys sys.path.append('../..') #", "# './' is necessary when running this file, but should be removed if", "in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice =", "list_temperature2 col = 1 row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] =", "list_time for row in [2, 5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row,", "= L self.data['K'] = K def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0']", "print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K", "row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row =", "voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0", "temp_ice row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws", "list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ']", "GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20',", "[] list_weight = [] for row in [1, 4, 7]: for col in", "7, 10]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else:", "print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end", "for row in [3, 6, 9, 12]: for col in range(1, 9): if", "输入excel的文件名 @return none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time", "= self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x = []", "= list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38)))", "= self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0 =", "resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x = [] list_y =", "= list_temperature2 col = 1 row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2']", "self.data['list_resistance'] = list_resistance for row in [3, 6, 9]: for col in range(1,", "row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15", "input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper != '1' and oper != '2':", "in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] =", "oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME)", "from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [", "self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1]", "self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0]", "self.data['UJ'] = UJ def fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i", "c0*temp_end + ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L']", "list_resistance2 = [] list_temperature2 = [] for row in [1, 4, 7, 10]:", "row in [1, 4, 7, 10]: for col in range(1, 9): if isinstance(ws.cell_value(row,", "!= '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif", "= voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row", "self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end']", "in [3, 6, 9, 12]: for col in range(1, 9): if isinstance(ws.cell_value(row, col),", "range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row in [2, 5,", "1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row =", "else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in [3, 6, 9, 12]:", "15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16 resitence =", "for i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x", "= self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence =", "16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] =", "if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") #", "= self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW =", "list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col = 1 for row in range(10,", "+ 64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy for i, x_i in", "list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end", "list_temperature2 = [] for row in [1, 4, 7, 10]: for col in", "+ ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] =", "break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False)", "- list_weight[0] list_x = [] list_y = [] for i in range(len(list_temperature2)): if", "''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def input_data(self, filename): ws =", "表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i)", "range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2", "list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] =", "m_water = list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a", "list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water", "'21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME", "print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end +", "print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice", "self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this file, but should be removed", "self.data['temp_env2'] = temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin", "= Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0] +", "self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") '''", "# 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择: \").strip()", "= list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38))", "i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 =", "ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ]", "self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0']", "= self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci =", "[1, 4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] =", "sys.exit(0) if oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if", "list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] *", "in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row in [3,", "def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data", "col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in [3,", "= list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0] *", "list_weight[0] list_x = [] list_y = [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1:", "list_x = [] list_y = [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break", "= [] list_y = [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2)", "'1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\")", "and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\")", "in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] =", "= self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] - list_weight[0]", "print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def input_data(self, filename): ws", "= [] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin =", "= list_resistance2 for row in [3, 6, 9, 12]: for col in range(1,", "import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys", "* (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def calc_data2(self): c1", "从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this file, but should be", "list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row in [3, 6, 9]: for", "如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter", "col))) #电阻值 self.data['list_resistance'] = list_resistance for row in [3, 6, 9]: for col", "c2 = self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] -", "ci = self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1]", "self.data['list_time'] = list_time for row in [2, 5, 8]: for col in range(1,", "row in [2, 5, 8, 11]: for col in range(1, 9): if isinstance(ws.cell_value(row,", "col))) self.data['list_temperature2'] = list_temperature2 col = 1 row = 13 temp_env2 = float(ws.cell_value(row,", "in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i ==", "list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2])", "list_weight = [] for row in [1, 4, 7]: for col in range(1,", "self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1]", "8, 11]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else:", "ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2 = [] for", "for row in [2, 5, 8, 11]: for col in range(1, 9): if", "\"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {} #", "\"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度", "self.data['list_temperature2'] = list_temperature2 col = 1 row = 13 temp_env2 = float(ws.cell_value(row, col))", "#电阻值 self.data['list_resistance'] = list_resistance for row in [3, 6, 9]: for col in", "= 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row", "self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__ == '__main__': mc =", "list_a = [] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin", "'./' is necessary when running this file, but should be removed if run", "self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence']", "= temp_ice row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env", "self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1])", "UJ def fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)]", "for row in [2, 5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col)))", "/ ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def calc_data2(self): c1 = self.data['c1']", "= Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ", "necessary when running this file, but should be removed if run main.py print(\"数据读入完毕,处理中......\")", "= list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n", "c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2", "[ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME =", "self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end']", "float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] =", "voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] -", "= list_temperature col = 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight']", "== '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件", "\").strip() except EOFError: sys.exit(0) if oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\")", "row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14", "list_y = [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i", "abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import", "sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter", "\"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty =", "list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0])", "list_resistance for row in [3, 6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row,", "= abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy for i,", "self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci']", "oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper ==", "= [] list_weight = [] for row in [1, 4, 7]: for col", "[] list_resistance = [] list_temperature = [] list_weight = [] for row in", "row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws =", "self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 =", "!= '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1':", "= float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0']", "list_graph[0] * list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin']", "self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__ ==", "self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x = [] list_y", "+ list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end']", "list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2']", "# 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True:", "[] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)):", "True: try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if oper != '1'", "row in [3, 6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度", "# 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME)", "= self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water =", "import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from", "= J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a =", "'2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper", "8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row in [3, 6, 9]:", "= resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] =", "= self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end =", "resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3", "for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row", "def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight =", "= self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x = [] list_y = []", "print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)-", "self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i", "9, 12]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else:", "row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice", "[] list_y = [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for", "range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col = 1 for row", "= [] for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in", "存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try:", "# 从excel中读取数据 list_time = [] list_resistance = [] list_temperature = [] list_weight =", "[] list_temperature2 = [] for row in [1, 4, 7, 10]: for col", "calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 = self.data['list_graph2']", "self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if", "- list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0]", "] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\"", "list_time1[0] + list_graph[1] temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin", "self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2.", "6, 9]: for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature", "float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin']", "L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0", "= self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight'] m_water =", "self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self):", "self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter()", "m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L =", "从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1')", "self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] =", "shutil import os from numpy import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句", "as xlscopy import shutil import os from numpy import sqrt, abs import sys", "from numpy import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import", "list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua =", "def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance =", "= 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight']", "- list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a'])", "in [2, 5, 8, 11]: for col in range(1, 9): if isinstance(ws.cell_value(row, col),", "range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice = float(ws.cell_value(row,", "= self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight =", "self.data['voltage_begin'] = voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end", "'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME", "UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy for", "= self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__", "[] for row in [1, 4, 7, 10]: for col in range(1, 9):", "= self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i in", "[] for row in [1, 4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row,", "Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0] + list_graph[1]", "1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 * m_water*0.001", "list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end", "Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys =", "= float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col))", "\"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] =", "self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J =", "else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1 row = 13 temp_env2", "9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col", "存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择: \").strip() except", "13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin =", "sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib", "(x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i)", "if oper != '1' and oper != '2': print(\"输入内容非法!请输入一个数字1或2\") else: break if oper", "[] list_temperature = [] list_weight = [] for row in [1, 4, 7]:", "11]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row,", "REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量", "list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in [2, 5, 8, 11]: for", "''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001)", "import os from numpy import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from", "col))) self.data['list_resistance2'] = list_resistance2 for row in [3, 6, 9, 12]: for col", "= float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env = float(ws.cell_value(row,", "\"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\"", "#温度 self.data['list_temperature'] = list_temperature col = 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col)))", "= self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 =", "in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] =", "m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K def calc_data2(self):", "= \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self):", "self.data['list_time2'] = list_time2 for row in [2, 5, 8, 11]: for col in", "col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 =", "print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") #", "col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度", "temp_env2 row = 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row =", "str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1 row =", "input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this file, but", "self.data['c0'] list_weight = self.data['list_weight'] m_water = list_weight[1] - list_weight[0] for i in range(len(list_x)):", "in [1, 4, 7, 10]: for col in range(1, 9): if isinstance(ws.cell_value(row, col),", "== len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x,", "#环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = []", "[2, 5, 8, 11]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str):", "list_weight[1] - list_weight[0] list_x = [] list_y = [] for i in range(len(list_temperature2)):", "GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import ReportWriter class thermology:", "c1 = self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water", "计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename:", "* list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water", "filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance = [] list_temperature", "10]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row,", "col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col = 1", "= list_x self.data['list_y'] = list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2", "main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report()", "self.data['temp_ice'] = temp_ice row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] =", "for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col)))", "range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i == len(list_temperature2)-1:", "in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for i, y_i in", "range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2", "col))) #温度 self.data['list_temperature'] = list_temperature col = 1 for row in range(10, 14):", "self.data['K'] = K def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 =", "= \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty", "= list_weight[1] - list_weight[0] list_x = [] list_y = [] for i in", "for i in range(len(list_temperature2)): if i==len(list_temperature2)-1: break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if", "file, but should be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2()", "{} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的", "64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']):", "= list_time for row in [2, 5, 8]: for col in range(1, 8):", "self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper", "voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16 resitence = float(ws.cell_value(row,", "ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance = [] list_temperature =", "生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none '''", "temp_begin self.data['temp_end'] = temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end)", "= Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self): #", "'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME =", "a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y", "resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3", "4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time", "if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row", "self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2", "= [] for row in [1, 4, 7, 10]: for col in range(1,", "* (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) /", "row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16", "从excel中读取数据 list_time = [] list_resistance = [] list_temperature = [] list_weight = []", "@return none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time =", "= list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water']", "= self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 =", "'118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\"", "c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K'] = K", "os from numpy import sqrt, abs import sys sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib", "r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y = self.data['list_y']", "self.data['list_weight'] = list_weight row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] =", "row in [3, 6, 9, 12]: for col in range(1, 9): if isinstance(ws.cell_value(row,", "% (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" %", "Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] =", "break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2': print(\"现在开始数据处理\")", "list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin = list_graph[0] * list_time1[0]", "''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K =", "= \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data = {}", "4, 7, 10]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue", "list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1", "list_y list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J']", "list_time = [] list_resistance = [] list_temperature = [] list_weight = [] for", "row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1'] = 0.389e3", "[3, 6, 9, 12]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str):", "self.data = {} # 存放实验中的各个物理量 self.uncertainty = {} # 存放物理量的不确定度 self.report_data = {}", "col)) self.data['voltage_end'] = voltage_end row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] =", "101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K']", "xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2 = [] for row in", "list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice = float(ws.cell_value(row, col)) #冰温度", "list_time2 for row in [2, 5, 8, 11]: for col in range(1, 9):", "def calc_uncertainty(self): list_a = [] list_x = self.data['list_x'] list_y = self.data['list_y'] list_graph2 =", "print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\")", "copy as xlscopy import shutil import os from numpy import sqrt, abs import", "for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14", "= self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0]", "os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def input_data(self, filename):", "1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice", "enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L']", "self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1']", "self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW", "xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance = [] list_temperature = [] list_weight", "#冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env']", "self.data['c1'] = 0.389e3 self.data['c2'] = 0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def", "# from xlutils.copy import copy as xlscopy import shutil import os from numpy", "temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2 = []", "(c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8])", "(y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua']", "continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in [3, 6, 9,", "= 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin", "= temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2 = [] list_temperature2 =", "= \"thermology_out.docx\" def __init__(self): self.data = {} # 存放实验中的各个物理量 self.uncertainty = {} #", "1 row = 13 temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row =", "(temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env))", "for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] =", "= self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 =", "# 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] =", "= {} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\")", "col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] =", "col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in [2,", "= list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph'] = list_graph temp_begin", "self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1']", "list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1 row = 13 temp_env2 =", "= 14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15", "list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin", "= \"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] =", "= xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = [] list_resistance = [] list_temperature = []", "9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for", "= [] for row in [1, 4, 7]: for col in range(1, 8):", "5, 8, 11]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue", "col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for row in", "float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end']", "# 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告 self.fill_report() print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param", "c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2", "temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env =", "temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 =", "{} # 存放物理量的不确定度 self.report_data = {} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while", "self.data['c1'] c2 = self.data['c2'] c0 = self.data['c0'] ci = self.data['ci'] m_water = list_weight[1]", "* (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) * (temp_begin-temp_end)- c0*temp_end + ci*temp_ice K = c0 * m_water*0.001 *", "voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end = float(ws.cell_value(row,", "list_time2 = [] list_resistance2 = [] list_temperature2 = [] for row in [1,", "thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME =", "[2, 5, 8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] =", "calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight = self.data['list_weight']", "self.report_data[str(i + 101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] = self.data['L'] self.report_data['K']", "list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end self.data['m_water'] =", "from xlutils.copy import copy as xlscopy import shutil import os from numpy import", "'101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME =", "range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ =", "os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this file,", "15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2", "row in [1, 4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间", "m_water = list_weight[1] - list_weight[0] list_x = [] list_y = [] for i", "# 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" %", "isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col = 1", "class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME", "c0 = self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice =", "= list_resistance for row in [3, 6, 9]: for col in range(1, 8):", "= list_time2 for row in [2, 5, 8, 11]: for col in range(1,", "= temp_end self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice)", "print(\"实验报告生成完毕,正在打开......\") os.startfile(self.REPORT_OUTPUT_FILENAME) print(\"Done!\") ''' 从excel表格中读取数据 @param filename: 输入excel的文件名 @return none ''' def input_data(self,", "temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence", "m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1,", "self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ']", "print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end) print('\\n!4!\\n',ci*temp_ice) ''' L = 1/(m_ice*0.001) * (c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001)", "[1, 4, 7, 10]: for col in range(1, 9): if isinstance(ws.cell_value(row, col), str):", "= 14 voltage_begin = float(ws.cell_value(row, col)) self.data['voltage_begin'] = voltage_begin row = 15 voltage_end", "xlscopy import shutil import os from numpy import sqrt, abs import sys sys.path.append('../..')", "14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight row = 14 temp_ice = float(ws.cell_value(row, col))", "for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row", "8]: for col in range(1, 8): list_resistance.append(float(ws.cell_value(row, col))) #电阻值 self.data['list_resistance'] = list_resistance for", "i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y']", "filename: 输入excel的文件名 @return none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据", "float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence']", "'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\"", "= self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__ == '__main__': mc", "最终结果 self.report_data['L'] = self.data['L'] self.report_data['K'] = self.data['K'] self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua']", "self.data['list_y'] list_graph2 = self.data['list_graph2'] voltage_begin = self.data['voltage_begin'] voltage_end = self.data['voltage_end'] resitence = self.data['resitence']", "= [] list_temperature2 = [] for row in [1, 4, 7, 10]: for", "list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row in [2, 5, 8]: for", "self.data['c0'] ci = self.data['ci'] m_water = list_weight[1] - list_weight[0] m_ice = list_weight[2] -", "+ 1)] = \"%.5f\" % (x_i) for i, y_i in enumerate(self.data['list_y']): self.report_data[str(i +", "float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2') list_time2 = [] list_resistance2", "self.data['voltage_end'] resitence = self.data['resitence'] c1 = self.data['c1'] c0 = self.data['c0'] list_weight = self.data['list_weight']", "in [1, 4, 7]: for col in range(1, 8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time']", "Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def fill_report(self): # 表格:xy", "# 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this file, but should", "= [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129', 'L','K','J', 'Ua','UJ' ] PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME", "col))) #时间 self.data['list_time'] = list_time for row in [2, 5, 8]: for col", "col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2']", "list_graph2 = Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] =", "fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\"", "i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for i,", "J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) '''", "14 temp_ice = float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env", "= 15 temp_env = float(ws.cell_value(row, col)) #环境温度 self.data['temp_env'] = temp_env ws = xlrd.open_workbook(filename).sheet_by_name('thermology2')", "running this file, but should be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量", "= UJ def fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i +", "- list_weight[0] m_ice = list_weight[2] - list_weight[1] list_graph = Fitting.linear(list_time1, list_temperature1, show_plot=False) self.data['list_graph']", "when running this file, but should be removed if run main.py print(\"数据读入完毕,处理中......\") #", "= float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16 resitence = float(ws.cell_value(row, col))", "voltage_end = self.data['voltage_end'] resitence = self.data['resitence'] m_water = list_weight[1] - list_weight[0] list_x =", "x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] = \"%.5f\" % (x_i) for i, y_i", "float(ws.cell_value(row, col)) #冰温度 self.data['temp_ice'] = temp_ice row = 15 temp_env = float(ws.cell_value(row, col))", "run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\") # 生成实验报告", "K def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2'] list_weight", "str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in [2, 5,", "break list_x.append((list_temperature2[i]+list_temperature2[i+1])/2-temp_env2) for i in range(len(list_temperature2)): if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x']", "else: break if oper == '1': print(\"现在开始实验预习\") print(\"正在打开预习报告......\") os.startfile(self.PREVIEW_FILENAME) elif oper == '2':", "removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度 self.calc_uncertainty() print(\"正在生成实验报告......\")", "0.389e3 self.data['c0'] = 4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1", "self.data['m_water'] = m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end)", "should be removed if run main.py print(\"数据读入完毕,处理中......\") # 计算物理量 self.calc_data1() self.calc_data2() # 计算不确定度", "none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') # 从excel中读取数据 list_time = []", "in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col = 1 for", "xlutils.copy import copy as xlscopy import shutil import os from numpy import sqrt,", "'2': print(\"现在开始数据处理\") print(\"即将打开数据输入文件......\") # 打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is", "= list_weight[1] - list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua", "= [] list_resistance2 = [] list_temperature2 = [] for row in [1, 4,", "{} # 存放需要填入实验报告的 print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择:", "range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2", "show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n", "K = c0 * m_water*0.001 * (list_temperature1[15]-list_temperature1[8]) / ((list_time1[15]-list_time1[8])*(list_temperature1[15]-temp_env)) self.data['L'] = L self.data['K']", "# 如果最终要从main.py调用,则删掉这句 from GeneralMethod.PyCalcLib import Fitting from GeneralMethod.PyCalcLib import Method from reportwriter.ReportWriter import", "self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME) if __name__ == '__main__':", "= m_water self.data['m_ice'] = m_ice ''' print(temp_begin) print('\\n',temp_end) print('\\n',m_water) print('\\n',m_ice) print('!1!\\n',c0*m_water*0.001+c1*list_weight[3]*0.001+c2*(list_weight[0]-list_weight[3])*0.001) print('\\n!2!\\n',temp_begin-temp_end) print('\\n!3!\\n',c0*temp_end)", "8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col = 1 for row in", "self.data['list_temperature'] temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2']", "for col in range(1, 8): list_temperature.append(float(ws.cell_value(row, col))) #温度 self.data['list_temperature'] = list_temperature col =", "= voltage_end row = 16 resitence = float(ws.cell_value(row, col)) self.data['resitence'] = resitence self.data['c1']", "temp_ice = self.data['temp_ice'] temp_env = self.data['temp_env'] c1 = self.data['c1'] c2 = self.data['c2'] c0", "打开数据输入文件 os.startfile(self.DATA_SHEET_FILENAME) input(\"输入数据完成后请保存并关闭excel文件,然后按回车键继续\") # 从excel中读取数据 self.input_data(\"./\"+self.DATA_SHEET_FILENAME) # './' is necessary when running this", "if i == len(list_temperature2)-1: break list_y.append((list_temperature2[i+1]-list_temperature2[i])/((list_time2[i+1]-list_time2[i])*60)) self.data['list_x'] = list_x self.data['list_y'] = list_y list_graph2", "y_i in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L']", "self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data) RW.fill_report(self.REPORT_TEMPLATE_FILENAME, self.REPORT_OUTPUT_FILENAME)", "@param filename: 输入excel的文件名 @return none ''' def input_data(self, filename): ws = xlrd.open_workbook(filename).sheet_by_name('thermology1') #", "xlrd # from xlutils.copy import copy as xlscopy import shutil import os from", "Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua UJ = abs(((voltage_begin+voltage_end)/2)**2/(Ua*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001 + 64.38))) self.data['UJ'] = UJ def", "from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117', '118','119','120','121','122','123','124','125','126','127','128','129',", "self.report_data['J'] = self.data['J'] self.report_data['Ua'] = self.data['Ua'] self.report_data['UJ'] = self.data['UJ'] RW = ReportWriter() RW.load_replace_kw(self.report_data)", "for col in range(1, 9): if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col)))", "isinstance(ws.cell_value(row, col), str): continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in", "print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x = self.data['list_x']", "Method from reportwriter.ReportWriter import ReportWriter class thermology: report_data_keys = [ '1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20', '21','22','23','24','25','26','27','28','29', '101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117',", "4.18e3 self.data['ci'] = 1.80e3 def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1", "实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择: \").strip() except EOFError: sys.exit(0) if", "if isinstance(ws.cell_value(row, col), str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row", "def fill_report(self): # 表格:xy for i, x_i in enumerate(self.data['list_x']): self.report_data[str(i + 1)] =", "continue else: list_time2.append(float(ws.cell_value(row, col))) self.data['list_time2'] = list_time2 for row in [2, 5, 8,", "self.data['list_temperature2'] list_weight = self.data['list_weight'] temp_env2 = self.data['temp_env2'] list_time2 = self.data['list_time2'] voltage_begin = self.data['voltage_begin']", "DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def __init__(self): self.data =", "= K def calc_data2(self): c1 = self.data['c1'] c0 = self.data['c0'] list_temperature2 = self.data['list_temperature2']", "8): list_time.append(float(ws.cell_value(row, col))) #时间 self.data['list_time'] = list_time for row in [2, 5, 8]:", "if isinstance(ws.cell_value(row, col), str): continue else: list_temperature2.append(float(ws.cell_value(row, col))) self.data['list_temperature2'] = list_temperature2 col =", "= 15 voltage_end = float(ws.cell_value(row, col)) self.data['voltage_end'] = voltage_end row = 16 resitence", "print(\"1021 测量水的溶解热+焦耳热功当量\\n1. 实验预习\\n2. 数据处理\") while True: try: oper = input(\"请选择: \").strip() except EOFError:", "temp_end = list_graph[0] * list_time1[(len(list_time1)-1)] + list_graph[1] self.data['temp_begin'] = temp_begin self.data['temp_end'] = temp_end", "in enumerate(self.data['list_y']): self.report_data[str(i + 101)] = \"%.5f\" % (y_i) # 最终结果 self.report_data['L'] =", "list_weight[0] for i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua']", "PREVIEW_FILENAME = \"Preview.pdf\" DATA_SHEET_FILENAME = \"data.xlsx\" REPORT_TEMPLATE_FILENAME = \"thermology_empty.docx\" REPORT_OUTPUT_FILENAME = \"thermology_out.docx\" def", "is necessary when running this file, but should be removed if run main.py", "Fitting.linear(list_x, list_y, show_plot=False) self.data['list_graph2'] = list_graph2 J = ((voltage_begin+voltage_end)/2)**2/(list_graph2[1]*resitence*(c0*m_water*0.001+c1*list_weight[3]*0.001+64.38)) self.data['J'] = J '''", "self.data['J'] = J ''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a", "temp_env2 = float(ws.cell_value(row, col)) self.data['temp_env2'] = temp_env2 row = 14 voltage_begin = float(ws.cell_value(row,", "i in range(len(list_x)): list_a.append(list_y[i]-list_graph2[1]*list_x[i]) self.data['list_a'] = list_a Ua = Method.a_uncertainty(self.data['list_a']) self.data['Ua'] = Ua", "''' print('b',list_graph2[0]) print('\\n a',list_graph2[1]) print('\\n r',list_graph2[2]) ''' def calc_uncertainty(self): list_a = [] list_x", "col = 1 for row in range(10, 14): list_weight.append(float(ws.cell_value(row,col))) #几种质量 self.data['list_weight'] = list_weight", "def calc_data1(self): list_weight = self.data['list_weight'] list_time1 = self.data['list_time'] list_temperature1 = self.data['list_temperature'] temp_ice =", "str): continue else: list_resistance2.append(float(ws.cell_value(row, col))) self.data['list_resistance2'] = list_resistance2 for row in [3, 6," ]
[ "absolute_import, unicode_literals from django.conf.urls import include, url from wagtail.admin import urls as wagtailadmin_urls", "wagtail.core import urls as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns =", "import include, url from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls", "wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls", "from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from", "urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtaildocs_previews import urls", "as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)),", "urls as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/',", "unicode_literals from django.conf.urls import include, url from wagtail.admin import urls as wagtailadmin_urls from", "django.conf.urls import include, url from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import", "from __future__ import absolute_import, unicode_literals from django.conf.urls import include, url from wagtail.admin import", "wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'',", "include, url from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as", "import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtaildocs_previews import", "<gh_stars>10-100 from __future__ import absolute_import, unicode_literals from django.conf.urls import include, url from wagtail.admin", "import absolute_import, unicode_literals from django.conf.urls import include, url from wagtail.admin import urls as", "urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'', include(wagtail_urls)), ]", "from django.conf.urls import include, url from wagtail.admin import urls as wagtailadmin_urls from wagtail.core", "as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtaildocs_previews import urls as", "from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)),", "__future__ import absolute_import, unicode_literals from django.conf.urls import include, url from wagtail.admin import urls", "import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'', include(wagtail_urls)),", "wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/',", "import urls as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns = [", "from wagtail.core import urls as wagtail_urls from wagtaildocs_previews import urls as wagtaildocs_urls urlpatterns", "url from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls", "wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtaildocs_previews" ]
[ "[c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id)", "sure only posts a user can read will be returned. \"\"\" def filter_queryset(self,", "on provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model", "Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend):", "lookup_type='gt', label='filter posts posted after given post id') dflabel = 'filter posts posted", "created before or on provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label)", "unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what", "letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters", "datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before or on", "least read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return", "CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is public ?') ca_label =", "django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework", "dflabel = 'filter posts posted after or on provided date / time' datefrom", "ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted in a channel are not", "/ time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before", "label='filter posts posted after given post id') dflabel = 'filter posts posted after", "-*- coding: utf-8 -*- from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from", "are not visible for anyone. This filter makes sure only posts a user", "= CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is public ?') ca_label", "contain filter') public = BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels created", "= DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created before or on provided", "user can read will be returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids", "def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name", "utf-8 -*- from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import", "readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return", "on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post", "\"\"\" All users cannot see what they want. They are restricted to see", "\"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet):", "Since channels have permissions, posts posted in a channel are not visible for", "class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted in a channel are", "= DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta:", "('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted", "posted after given post id') dflabel = 'filter posts posted after or on", "a list of channel ids on which user given in parameter has at", "users cannot see what they want. They are restricted to see only channels", "in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users", "label='author contain filter') type = CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type',", "label=ca_label) class Meta: model = Channel fields = ('name', 'public', 'created_after', 'created_before',) class", "queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type',", "content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model = Post fields", "on which they have at least read_channel permission. \"\"\" def filter_queryset(self, request, queryset,", "label=dflabel) dtlabel = 'filter posts posted before or on provided date / time'", "see what they want. They are restricted to see only channels on which", "CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model = Post fields = ('author',", "on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel',", "import filters from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list", "permission. It also includes public channels, where anyone can read/write on. Channel ids", "= DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before or on provided", "set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they want.", "import get_objects_for_user from rest_framework import filters from chat.models import Post, Channel def get_readable_channel_ids(user):", "on provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter", "/ time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain", "= get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter')", "see only channels on which they have at least read_channel permission. \"\"\" def", "after given post id') dflabel = 'filter posts posted after or on provided", "value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters posts", "unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c in", "for anyone. This filter makes sure only posts a user can read will", "read_channel permission. It also includes public channels, where anyone can read/write on. Channel", "= get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c in readable_channels] public_channels =", "= CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model = Post fields =", "DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model", "Meta: model = Channel fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\"", "on provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter", "read will be returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user)", "given in parameter has at least read_channel permission. It also includes public channels,", "label='is public ?') ca_label = 'filter channels created after or on provided date", "get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type", "lookup_type='gte', label=ca_label) cb_label = 'filter channels created before or on provided date /", "content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters posts sent", "get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public", "channels created after or on provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte',", "provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model =", "will be returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return", "filter') public = BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels created after", "read/write on. Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids", "channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post id') dflabel", "which they have at least read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view):", "= CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter on letter value')", "time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created before or", "\"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet):", "lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is public ?') ca_label = 'filter", "in parameter has at least read_channel permission. It also includes public channels, where", "list of channel ids on which user given in parameter has at least", "ca_label = 'filter channels created after or on provided date / time' created_after", "a channel are not visible for anyone. This filter makes sure only posts", "anyone. This filter makes sure only posts a user can read will be", "label='content contain filter') channel = NumberFilter(name='channel', label='filters posts sent on provided channel') afterid", "queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public',", "name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is public ?')", "can read will be returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids =", "/ time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created before", "date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel", "lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before or on provided date /", "= 'filter posts posted before or on provided date / time' dateto =", "posted after or on provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel)", "/ time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel fields", "only posts a user can read will be returned. \"\"\" def filter_queryset(self, request,", "cannot see what they want. They are restricted to see only channels on", "provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels", "channel = NumberFilter(name='channel', label='filters posts sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt',", "CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters posts sent on provided", "at least read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user)", "'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted in", "are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c", "posts posted after given post id') dflabel = 'filter posts posted after or", "\"\"\" Since channels have permissions, posts posted in a channel are not visible", "request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name',", "queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains',", "dtlabel = 'filter posts posted before or on provided date / time' dateto", "def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author", "= BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels created after or on", "user given in parameter has at least read_channel permission. It also includes public", "to see only channels on which they have at least read_channel permission. \"\"\"", "view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name", "readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain", "= 'filter channels created after or on provided date / time' created_after =", "id') dflabel = 'filter posts posted after or on provided date / time'", "channels on which they have at least read_channel permission. \"\"\" def filter_queryset(self, request,", "from guardian.shortcuts import get_objects_for_user from rest_framework import filters from chat.models import Post, Channel", "channel ids on which user given in parameter has at least read_channel permission.", "have at least read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids =", "want. They are restricted to see only channels on which they have at", "ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they want. They are restricted to", "channel are not visible for anyone. This filter makes sure only posts a", "return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they want. They", "they have at least read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids", "anyone can read/write on. Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel',", "date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created", "It also includes public channels, where anyone can read/write on. Channel ids are", "not visible for anyone. This filter makes sure only posts a user can", "'filter posts posted before or on provided date / time' dateto = DateTimeFilter(name='date',", "before or on provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class", "from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list of channel", "are restricted to see only channels on which they have at least read_channel", "time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter')", "or on provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label =", "date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted", "includes public channels, where anyone can read/write on. Channel ids are unique. \"\"\"", "get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True)", "return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type =", "\"\"\" Return a list of channel ids on which user given in parameter", "time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel fields =", "contain filter') channel = NumberFilter(name='channel', label='filters posts sent on provided channel') afterid =", "= Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class", "CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel", "label='filters posts sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted", "on provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content',", "class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they want. They are restricted", "label=ca_label) cb_label = 'filter channels created before or on provided date / time'", "Channel def get_readable_channel_ids(user): \"\"\" Return a list of channel ids on which user", "lookup_type='lte', label=ca_label) class Meta: model = Channel fields = ('name', 'public', 'created_after', 'created_before',)", "# -*- coding: utf-8 -*- from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter)", "filter') type = CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content", "BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels created after or on provided", "lookup_type='icontains', label='content contain filter') class Meta: model = Post fields = ('author', 'type',", "= Channel fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels", "posts a user can read will be returned. \"\"\" def filter_queryset(self, request, queryset,", "= DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel fields = ('name', 'public',", "read_channel permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids)", "DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel fields = ('name', 'public', 'created_after',", "readable_ids = [c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in", "after or on provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel", "parameter has at least read_channel permission. It also includes public channels, where anyone", "sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given", "visible for anyone. This filter makes sure only posts a user can read", "or on provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel =", "use_groups=True) readable_ids = [c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel", "readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain", "also includes public channels, where anyone can read/write on. Channel ids are unique.", "posts posted after or on provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte',", "ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is public", "public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids", "label='name contain filter') public = BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels", "permissions, posts posted in a channel are not visible for anyone. This filter", "they want. They are restricted to see only channels on which they have", "readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c in readable_channels] public_channels", "in a channel are not visible for anyone. This filter makes sure only", "unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they want. They are", "posts sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after", "rest_framework import filters from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a", "All users cannot see what they want. They are restricted to see only", "(FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import filters", "cb_label = 'filter channels created before or on provided date / time' created_before", "time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before or", "class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter", "They are restricted to see only channels on which they have at least", "at least read_channel permission. It also includes public channels, where anyone can read/write", "filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name =", "provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains',", "'chat.read_channel', use_groups=True) readable_ids = [c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True) for", "afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post id') dflabel =", "of channel ids on which user given in parameter has at least read_channel", "= 'filter channels created before or on provided date / time' created_before =", "coding: utf-8 -*- from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts", "def get_readable_channel_ids(user): \"\"\" Return a list of channel ids on which user given", "PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter on", "get_objects_for_user from rest_framework import filters from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\"", "ids on which user given in parameter has at least read_channel permission. It", "from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from", "can read/write on. Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True)", "= NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post id') dflabel = 'filter", "label='content contain filter') class Meta: model = Post fields = ('author', 'type', 'content',", "BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import filters from chat.models import Post,", "only channels on which they have at least read_channel permission. \"\"\" def filter_queryset(self,", "guardian.shortcuts import get_objects_for_user from rest_framework import filters from chat.models import Post, Channel def", "public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot", "on. Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids =", "for c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids", "class Meta: model = Channel fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend):", "public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All", "import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import", "contain filter') type = CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains',", "permission. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(id__in=readable_channel_ids) class", "created after or on provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label)", "least read_channel permission. It also includes public channels, where anyone can read/write on.", "return queryset.filter(id__in=readable_channel_ids) class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public =", "= CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters posts sent on", "channels have permissions, posts posted in a channel are not visible for anyone.", "?') ca_label = 'filter channels created after or on provided date / time'", "fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions,", "view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author", "CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import filters from", "lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model =", "chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list of channel ids", "CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter on letter value') content", "where anyone can read/write on. Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user,", "in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids)", "NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post id') dflabel = 'filter posts", "DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts posted before or on provided date", "given post id') dflabel = 'filter posts posted after or on provided date", "returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class", "'filter channels created after or on provided date / time' created_after = DateTimeFilter(name='date',", "from rest_framework import filters from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return", "date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content", "makes sure only posts a user can read will be returned. \"\"\" def", "'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted in a", "be returned. \"\"\" def filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids)", "provided date / time' datefrom = DateTimeFilter(name='date', lookup_type='gte', label=dflabel) dtlabel = 'filter posts", "dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class", "DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import filters from chat.models", "class ChannelFilter(FilterSet): name = CharFilter(name='name', lookup_type='icontains', label='name contain filter') public = BooleanFilter(name='public', label='is", "or on provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content =", "public ?') ca_label = 'filter channels created after or on provided date /", "ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for", "a user can read will be returned. \"\"\" def filter_queryset(self, request, queryset, view):", "label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter') channel =", "-*- from django_filters import (FilterSet, CharFilter, DateTimeFilter, NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user", "queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains',", "or on provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta:", "= NumberFilter(name='channel', label='filters posts sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter", "author = CharFilter(name='author', lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter on letter", "contain filter') class Meta: model = Post fields = ('author', 'type', 'content', 'datefrom',", "Channel fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have", "type = CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain", "DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created before or on provided date", "filter_queryset(self, request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author =", "= [c.id for c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels:", "= set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see what they", "have permissions, posts posted in a channel are not visible for anyone. This", "\"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id for c in readable_channels]", "request, queryset, view): readable_channel_ids = get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author',", "readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\" All users cannot see", "c in readable_channels] public_channels = Channel.objects.filter(public=True) for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids =", "channels created before or on provided date / time' created_before = DateTimeFilter(name='date', lookup_type='lte',", "NumberFilter(name='channel', label='filters posts sent on provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts", "public channels, where anyone can read/write on. Channel ids are unique. \"\"\" readable_channels", "'filter channels created before or on provided date / time' created_before = DateTimeFilter(name='date',", "provided channel') afterid = NumberFilter(name='id', lookup_type='gt', label='filter posts posted after given post id')", "= 'filter posts posted after or on provided date / time' datefrom =", "filter') class Meta: model = Post fields = ('author', 'type', 'content', 'datefrom', 'dateto',)", "posts posted before or on provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte',", "= get_readable_channel_ids(request.user) return queryset.filter(channel__in=readable_channel_ids) class PostFilter(FilterSet): author = CharFilter(name='author', lookup_type='icontains', label='author contain filter')", "created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label = 'filter channels created before or on", "'filter posts posted after or on provided date / time' datefrom = DateTimeFilter(name='date',", "lookup_type='icontains', label='author contain filter') type = CharFilter(name='type', label='filter on letter value') content =", "has at least read_channel permission. It also includes public channels, where anyone can", "This filter makes sure only posts a user can read will be returned.", "channels, where anyone can read/write on. Channel ids are unique. \"\"\" readable_channels =", "Return a list of channel ids on which user given in parameter has", "'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts posted in a channel", "NumberFilter, BooleanFilter) from guardian.shortcuts import get_objects_for_user from rest_framework import filters from chat.models import", "which user given in parameter has at least read_channel permission. It also includes", "filter makes sure only posts a user can read will be returned. \"\"\"", "after or on provided date / time' created_after = DateTimeFilter(name='date', lookup_type='gte', label=ca_label) cb_label", "on which user given in parameter has at least read_channel permission. It also", "before or on provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel) content", "Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list of channel ids on which", "what they want. They are restricted to see only channels on which they", "filters from chat.models import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list of", "lookup_type='icontains', label='content contain filter') channel = NumberFilter(name='channel', label='filters posts sent on provided channel')", "import Post, Channel def get_readable_channel_ids(user): \"\"\" Return a list of channel ids on", "created_before = DateTimeFilter(name='date', lookup_type='lte', label=ca_label) class Meta: model = Channel fields = ('name',", "model = Channel fields = ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since", "Channel ids are unique. \"\"\" readable_channels = get_objects_for_user(user, 'chat.read_channel', use_groups=True) readable_ids = [c.id", "posted in a channel are not visible for anyone. This filter makes sure", "posted before or on provided date / time' dateto = DateTimeFilter(name='date', lookup_type='lte', label=dtlabel)", "posts posted in a channel are not visible for anyone. This filter makes", "get_readable_channel_ids(user): \"\"\" Return a list of channel ids on which user given in", "for public_channel in public_channels: readable_ids.append(public_channel.id) unique_readable_ids = set(readable_ids) return unique_readable_ids class ReadableChannelFilter(filters.BaseFilterBackend): \"\"\"", "= CharFilter(name='type', label='filter on letter value') content = CharFilter(name='type', lookup_type='icontains', label='content contain filter')", "= ('name', 'public', 'created_after', 'created_before',) class ReadablePostFilter(filters.BaseFilterBackend): \"\"\" Since channels have permissions, posts", "public = BooleanFilter(name='public', label='is public ?') ca_label = 'filter channels created after or", "post id') dflabel = 'filter posts posted after or on provided date /", "label=dtlabel) content = CharFilter(name='content', lookup_type='icontains', label='content contain filter') class Meta: model = Post", "restricted to see only channels on which they have at least read_channel permission.", "filter') channel = NumberFilter(name='channel', label='filters posts sent on provided channel') afterid = NumberFilter(name='id'," ]
[ "as plt import torch import torch.nn as nn import torch.nn.functional as F from", "EventTruth object. \"\"\" def __init__(self, files): self.files = files self.event_data = None self.events", ".plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file \"\"\"", "self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event objects from", "data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth =", "An Event contains a Graph and an EventTruth object. It represents a unit", "out_edges.numpy() # Sort edges by increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask],", "is not None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self):", "n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\"", "np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO:", "event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles", "**kwargs): \"\"\" Plots evaluation of candidates \"\"\" if self.evaluation is None: raise ValueError(\"No", "tqdm.contrib.concurrent import process_map import networkx as nx from functools import partial from .tracking_utils", "ValueError(\"Unknown data type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges),", "self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs):", "not find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data", "self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building", "not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\"", "from scipy import sparse as sps from tqdm import tqdm from tqdm.contrib.concurrent import", "edge_mask = self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0))", "pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn", "**kwargs): \"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph():", "\"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try: particle_filename", "1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1]", "candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from event \"\"\"", "= Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data", "self.hit_truth is not None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def", "the detector, out_edges are the nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:,", "# Check if edge_index is in data for key in data.keys(): if (", "{n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\"", "Graph and an EventTruth object. \"\"\" def __init__(self, files): self.files = files self.event_data", "for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a Graph", "__iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event with Intersection over Union (IoU)", "that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates", "if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges =", "KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self,", "\"\"\" Loads a single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance,", "from graph \"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method", "def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates", "criteria. Criteria given by ratios of common hits in candidates (\"reconstructed\") and particles", "{ \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1", "Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self,", "particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from event with matching criteria. Criteria", "return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\":", "file type, there are still more file types to be added!\") def __load_pytorch_files(self):", "+ z**2) # in_edges are the nodes towards the inner of the detector,", "a Graph and an EventTruth object. \"\"\" def __init__(self, files): self.files = files", "else: raise NotImplementedError(\"Plotting not implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\",", "is not None assert self.graph_data is not None # Define representation def __repr__(self):", "evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events])", "plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\" if self.evaluation is", "{n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates", "in config\" # Check if x is in data for key in data.keys():", "self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles", "= None self.candidates = None self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes", "file list \"\"\" # data = [] # for file in tqdm(self.files): #", "\"\"\" Builds track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def", "data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track", "event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates", "= self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask]", "= process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds", "edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track", "**kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance", "file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self):", "self.particles = None self.hit_truth = None assert type(event_file) == str or type(event_file) ==", "TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0,", "are still more file types to be added!\") def __load_pytorch_files(self): \"\"\" Loads all", "{ \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks,", "type(data_dict) == dict, \"Data must be a dictionary\" self.__process_data(data_dict) # Test if data", "loaded assert self.hits is not None assert self.edges is not None assert self.graph_data", "self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N =", "n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks},", "__init__(self, event_file): self.particles = None self.hit_truth = None assert type(event_file) == str or", "{n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\" if", "else: raise ValueError(\"Unknown file type, this is not a Pytorch Geometric file\") except:", "return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph", "an EventTruth object. It represents a unit of particle physics data. \"\"\" def", "HIT ID IS USED CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file): self.particles", "self.__load_files() assert self.event_data is not None # Test if files are loaded logging.info(\"Building", "\"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth,", "used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle", "type, there are still more file types to be added!\") def __load_pytorch_files(self): \"\"\"", "track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\",", "def __init__(self, data): self.graph = None self.event_truth = None self.candidates = None self.data", "n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates", "except: raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit", "= np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths =", "ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data", "__len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to be used in", "score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges", "= self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays if (type(in_edges) != np.ndarray)", "k in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\"", "pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth file\") def", "= match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks,", "representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self,", "): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data", "import torch.nn.functional as F from scipy import sparse as sps from tqdm import", "data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method,", "n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\":", "Check if edge_index is in data for key in data.keys(): if ( len(data[key].shape)", "Sort edges by increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] =", "graph \"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method ==", "def __process_data(self, event_file): \"\"\" Processes data to be used in the pipeline \"\"\"", "Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\")", "need a feature called x, otherwise define default node feature in config\" #", "event_file): \"\"\" Returns particle data \"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles", "key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data):", "\"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self,", "\"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 -", "ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths", "in data for key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key]", "path in all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in", "= Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID IS USED CORRECTLY!!", "def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\")", "def __get_file_type(self): \"\"\" Determine type of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\")", "None self.edges = None self.graph_data = None assert type(data_dict) == dict, \"Data must", "ValueError(\"Could not find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth", "Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs)", "edge_mask] # Ensure edges are numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges)", "\"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def", "or type(event_file) == np.str_, \"Event file must be a string\" self.__process_data(event_file) # Test", "Builds Event objects from event data \"\"\" # self.events = [] # for", "this is not a Pytorch Geometric file\") except: raise ValueError(\"Unknown file type, there", "= self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5,", "# for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs):", "def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to be used", "data. \"\"\" def __init__(self, data): self.graph = None self.event_truth = None self.candidates =", "return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph \"\"\" raise", "# in_edges are the nodes towards the inner of the detector, out_edges are", "as sps from tqdm import tqdm from tqdm.contrib.concurrent import process_map import networkx as", "Test data loaded properly assert self.particles is not None assert self.hit_truth is not", "def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in file list \"\"\" #", "return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is not a Pytorch Geometric", "candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events =", "data loaded properly assert self.particles is not None assert self.hit_truth is not None", "os import sys import logging import numpy as np import pandas as pd", "data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False,", "\"\"\" Determine type of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample))", "be used in the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data)", "networkx as nx from functools import partial from .tracking_utils import * from .plotting_utils", "== \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file)", "self.events[idx] return event def __load_files(self): \"\"\" Loads files based on type \"\"\" file_type", "evaluation of candidates \"\"\" if self.evaluation is None: raise ValueError(\"No evaluation available\") if", "= self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file", "len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0]", "str or type(event_file) == np.str_, \"Event file must be a string\" self.__process_data(event_file) #", "self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\")", "__repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes", "A class that holds a list of Events, specifically for the tracking pipeline.", "of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles)", "= self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event objects", "file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown", "# self.events = [] # for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events =", "the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown", "build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for", "Builds track candidates from events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial", "= self.edges[\"scores\"] > score_cut # Order edges by increasing R r, phi, z", "n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0, 0 for event in self.events:", "+= event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\":", "event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles", "towards the inner of the detector, out_edges are the nodes towards the outer", "Pytorch Geometric file\") except: raise ValueError(\"Unknown file type, there are still more file", "\"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event():", "def __init__(self, event_file): self.particles = None self.hit_truth = None assert type(event_file) == str", "(n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = {", "added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in file list \"\"\"", "ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected", "self.graph_data = None assert type(data_dict) == dict, \"Data must be a dictionary\" self.__process_data(data_dict)", "as np import pandas as pd import matplotlib.pyplot as plt import torch import", "np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels", "\"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row,", "\"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks:", "str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file =", "# Ensure edges are numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges) !=", "if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def", "and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns", "self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a Graph and an EventTruth", "# Test if data is loaded assert self.hits is not None assert self.edges", "self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns", "all_paths[path] for path in all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for", "\"\"\" Returns all paths from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else:", "= event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks,", "data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\") # Define", "feature called edge_index, otherwise define default edge feature in config\" # Check if", "list \"\"\" # data = [] # for file in tqdm(self.files): # data.append(torch.load(file,", "n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks,", "# Test if files are loaded logging.info(\"Building events\") self.__build_events() assert self.events is not", "\"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def", "building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles /", "== dict, \"Data must be a dictionary\" self.__process_data(data_dict) # Test if data is", "**kwargs): \"\"\" Plots matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\")", "= None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None", "\"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else:", "build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph \"\"\" if building_method", "n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks,", "instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class that holds a list of", "= data.event_file) else: raise ValueError(\"Unknown data type\") # Define representation def __repr__(self): return", "functools import partial from .tracking_utils import * from .plotting_utils import * def load_single_pytorch_file(file):", "= 0, 0, 0, 0, 0, 0 for event in self.events: n_true_tracks +=", "particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\" try: hit_truth_filename", "__get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data = {k: data[k] for k", "**kwargs): \"\"\" Builds track candidates from graph \"\"\" if building_method == \"CC\": candidates", "\"Data must be a dictionary\" self.__process_data(data_dict) # Test if data is loaded assert", "else: raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\"", "self.events is not None # Test if events are built def __len__(self): return", "particle physics data. \"\"\" def __init__(self, data): self.graph = None self.event_truth = None", "map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type,", "type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles),", "\"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks /", "Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates", "self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges =", "Loads all Pytorch geometric files in file list \"\"\" # data = []", "building_method=\"AP\") # TODO: CHECK THAT HIT ID IS USED CORRECTLY!! return candidates class", "torch.nn.functional as F from scipy import sparse as sps from tqdm import tqdm", "= process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) #", "None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles)", "n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks", "USED CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth", "(N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\")", "with matching criteria. Criteria given by ratios of common hits in candidates (\"reconstructed\")", "of particle physics data. \"\"\" def __init__(self, data): self.graph = None self.event_truth =", "in all_paths[start_key].keys() if (start_key != end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths)))", "observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\",", "tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates", "track_ids self.building_method = building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\"", "from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits =", "unit of particle physics data. \"\"\" def __init__(self, data): self.graph = None self.event_truth", "= np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") #", "(\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks,", "\"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 -", "def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\" if method", "return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to be used in the", "__repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\"", "/ n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks:", "assert type(data_dict) == dict, \"Data must be a dictionary\" self.__process_data(data_dict) # Test if", "= hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation = None def __repr__(self):", "None # Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return", "self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown", "self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event", "Geometric file\") except: raise ValueError(\"Unknown file type, there are still more file types", "import * from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch", "self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut # Order edges by increasing R", "track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict):", "(n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles,", "objects from event data \"\"\" # self.events = [] # for data in", "default edge feature in config\" # Check if edge_index is in data for", "= nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for path", "n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates", "\"\"\" Returns hit truth data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth", "{n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation", "a Pytorch Geometric file\") except: raise ValueError(\"Unknown file type, there are still more", "self.edges = {} assert \"edge_index\" in data.keys(), \"At least need a feature called", "self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns hit data", "define default edge feature in config\" # Check if edge_index is in data", "\"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth)", "import sys import logging import numpy as np import pandas as pd import", "self.events = [] # for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event,", "logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events", "Processes data to be used in the pipeline \"\"\" if str(type(data)) == \"<class", "data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns graph", "self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays if (type(in_edges) != np.ndarray) or", "file type, this is not a Pytorch Geometric file\") except: raise ValueError(\"Unknown file", "THAT HIT ID IS USED CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file):", "self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to be used in the pipeline", "track candidates from event with Intersection over Union (IoU) \"\"\" raise NotImplementedError(\"IOU reconstruction", "self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\") # Define representation", "built def __len__(self): return len(self.events) def __getitem__(self, idx): event = self.events[idx] return event", "} return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event with", "self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of file \"\"\" try: sample =", "\"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits = None self.edges", "\"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\":", "graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs):", "build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building candidates", "import logging import numpy as np import pandas as pd import matplotlib.pyplot as", "a unit of particle physics data. \"\"\" def __init__(self, data): self.graph = None", "self.__build_events() assert self.events is not None # Test if events are built def", "in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by increasing R wrong_direction_mask = R[in_edges]", "row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges =", "None assert self.graph_data is not None # Define representation def __repr__(self): return f\"Graph(hits={self.hits},", "It represents a unit of particle physics data. \"\"\" def __init__(self, data): self.graph", "hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids", "n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0, 0 for", "self.events = None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not", "if (start_key != end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list =", "the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\"", "\"\"\" self.edges = {} assert \"edge_index\" in data.keys(), \"At least need a feature", "return event def __load_files(self): \"\"\" Loads files based on type \"\"\" file_type =", "self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track", "in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by increasing R wrong_direction_mask", "with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial,", "called edge_index, otherwise define default edge feature in config\" # Check if edge_index", "hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates():", "all_paths = {path: all_paths[path] for path in all_paths.keys() if path in starting_nodes} valid_paths", "return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes", "# Check if x is in data for key in data.keys(): if len(data[key])", "for key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self,", "(self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from", "data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from events \"\"\"", "not None assert self.graph_data is not None # Define representation def __repr__(self): return", "sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph \"\"\" if sanity_check: edge_mask", "Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df", "return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance", "def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df", "raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event objects from event data", "used in the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else:", "n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\":", "a Graph and an EventTruth object. It represents a unit of particle physics", "def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\" if self.evaluation", "= track_ids self.building_method = building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids},", "self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of file \"\"\"", "n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles},", "# Test if events are built def __len__(self): return len(self.events) def __getitem__(self, idx):", "1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks},", "called x, otherwise define default node feature in config\" # Check if x", "file types to be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files", "**kwargs): \"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates,", "torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def", "n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return", "ID IS USED CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file): self.particles =", "\"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\")", "self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges are the nodes towards the", "EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\") # Define representation def __repr__(self):", "edge feature in config\" # Check if edge_index is in data for key", "if edge_index is in data for key in data.keys(): if ( len(data[key].shape) >", "return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids", "= self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates)", "data to be used in the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\":", "in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key != end_key and end_key in", "all paths from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask =", "+= event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks +=", "of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self,", "def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\" try: hit_truth_filename = event_file", "sys import logging import numpy as np import pandas as pd import matplotlib.pyplot", "sanity_check=False, **kwargs): \"\"\" Builds track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check,", "assert self.graph_data is not None # Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges},", "instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class", "n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\")", "> score_cut # Order edges by increasing R r, phi, z = self.hits[\"x\"].T", "= data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\") #", "np.str_, \"Event file must be a string\" self.__process_data(event_file) # Test data loaded properly", "self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for", "def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth", "and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ):", "__len__(self): return len(self.events) def __getitem__(self, idx): event = self.events[idx] return event def __load_files(self):", "**kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\":", "graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut", "class that holds a list of Events, specifically for the tracking pipeline. An", "method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class", ".tracking_utils import * from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a single", "in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def", "Plots matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event", "n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of", "{n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\",", "None self.events = None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data is", "self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation", "z**2) # in_edges are the nodes towards the inner of the detector, out_edges", "self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None # Test", "__get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try: particle_filename = event_file + \"-particles.csv\"", "the inner of the detector, out_edges are the nodes towards the outer in_edges,", "\"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\"", "except: raise ValueError(\"Unknown file type, there are still more file types to be", "yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph \"\"\"", "holds a list of Events, specifically for the tracking pipeline. An Event contains", "\"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation", "return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from events", "= self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth file\") def __process_hit_truth(self, hit_truth):", "__getitem__(self, idx): event = self.events[idx] return event def __load_files(self): \"\"\" Loads files based", "candidates \"\"\" if self.evaluation is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] ==", "not None # Test if files are loaded logging.info(\"Building events\") self.__build_events() assert self.events", "inner of the detector, out_edges are the nodes towards the outer in_edges, out_edges", "= out_edges.numpy() # Sort edges by increasing R wrong_direction_mask = R[in_edges] > R[out_edges]", "building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return", "sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise", "matching criteria. Criteria given by ratios of common hits in candidates (\"reconstructed\") and", "build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles,", "plt import torch import torch.nn as nn import torch.nn.functional as F from scipy", "Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def", "truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids,", "data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns", "z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges are the nodes", "tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self,", "0, 0, 0, 0, 0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks", "= self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown", "__get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not", "a feature called edge_index, otherwise define default edge feature in config\" # Check", "len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self,", "and an EventTruth object. It represents a unit of particle physics data. \"\"\"", "hit_truth, **kwargs): \"\"\" Evaluates track candidates from event with matching criteria. Criteria given", "a dictionary\" self.__process_data(data_dict) # Test if data is loaded assert self.hits is not", "[] # for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1)", "candidates from events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates,", "data \"\"\" self.graph_data = {k: data[k] for k in data.keys() - (self.hits.keys() &", "= self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise", "n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs):", "track candidates from events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial =", "particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find", "n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation)", "return df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\"", "from event data \"\"\" # self.events = [] # for data in tqdm(self.event_data):", "np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn", "= {path: all_paths[path] for path in all_paths.keys() if path in starting_nodes} valid_paths =", "= np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates = Candidates(hit_list,", "in file list \"\"\" # data = [] # for file in tqdm(self.files):", "event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates", "candidates class EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth = None assert", "sparse as sps from tqdm import tqdm from tqdm.contrib.concurrent import process_map import networkx", "self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method ==", "n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event", "Ensure edges are numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray):", "a string\" self.__process_data(event_file) # Test data loaded properly assert self.particles is not None", "{path: all_paths[path] for path in all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key]", "on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains", "**kwargs): \"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building candidates with sanity check:", "1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\"", "len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns edge data", "assert \"x\" in data.keys(), \"At least need a feature called x, otherwise define", "return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to be used in the", "out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) #", "self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\"", "= np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph()", "arrays if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges", "files in file list \"\"\" # data = [] # for file in", "partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in", "= self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges,", "else: edge_mask = self.edges[\"scores\"] > score_cut # Order edges by increasing R r,", "= R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)])", "= in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by increasing R wrong_direction_mask =", "inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids =", "candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths", "= self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges are the nodes towards", "edges by increasing R r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 +", "for path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT", "== np.str_, \"Event file must be a string\" self.__process_data(event_file) # Test data loaded", "from event with matching criteria. Criteria given by ratios of common hits in", "if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file", "sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut # Order edges", "events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check,", "method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from event with", "up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0,", "in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths", "__load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in file list \"\"\" # data", "{k: data[k] for k in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\",", "event_file): \"\"\" Processes data to be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file)", "data to be used in the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data)", "pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try:", "np.sqrt(r**2 + z**2) # in_edges are the nodes towards the inner of the", "/ n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\":", "R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges,", "out_edges = out_edges.numpy() # Sort edges by increasing R wrong_direction_mask = R[in_edges] >", "candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method", "is not None # Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def", "edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to", "== \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs)", "**kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class that holds a list", "sps from tqdm import tqdm from tqdm.contrib.concurrent import process_map import networkx as nx", "self.hits = {} assert \"x\" in data.keys(), \"At least need a feature called", "__load_files(self): \"\"\" Loads files based on type \"\"\" file_type = self.__get_file_type() if file_type", "particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles,", "+ \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find", "import tqdm from tqdm.contrib.concurrent import process_map import networkx as nx from functools import", "is in data for key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] =", "be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns", "None assert self.hit_truth is not None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles},", "return instance class TrackingData(): \"\"\" A class that holds a list of Events,", "self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth file\") def __process_hit_truth(self,", "self.edges[\"scores\"] > score_cut # Order edges by increasing R r, phi, z =", "# for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1)", "events are built def __len__(self): return len(self.events) def __getitem__(self, idx): event = self.events[idx]", "def __init__(self, data_dict): self.hits = None self.edges = None self.graph_data = None assert", "in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\"", "ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event objects from event data \"\"\"", "evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs)", "particle data \"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except:", "\"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is not a Pytorch Geometric file\")", "- (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\":", "\"\"\" An Event contains a Graph and an EventTruth object. It represents a", "except: raise ValueError(\"Could not find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes", "import networkx as nx from functools import partial from .tracking_utils import * from", "process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO:", "self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\"", "TrackingData(): \"\"\" A class that holds a list of Events, specifically for the", "if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this", "end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in", "def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates \"\"\" all_particles", "try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else:", "\"\"\" Returns hit data \"\"\" self.hits = {} assert \"x\" in data.keys(), \"At", "- (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks:", "common hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(),", "def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from event \"\"\" self.candidates", "connected components from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask =", "string\" self.__process_data(event_file) # Test data loaded properly assert self.particles is not None assert", "self.graph_data = {k: data[k] for k in data.keys() - (self.hits.keys() & self.edges.keys())} def", "data = [] # for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data =", "__process_data(self, event_file): \"\"\" Processes data to be used in the pipeline \"\"\" self.__get_particle_data(event_file)", "pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns", "\"\"\" Builds Event objects from event data \"\"\" # self.events = [] #", "find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\"", "return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A", "if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates", "and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path", "types to be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in", "Loads a single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method,", "\"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for that method\")", "least need a feature called edge_index, otherwise define default edge feature in config\"", "R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes", "by ratios of common hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles,", "__repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns", "= out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build", "== \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for that", "from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\"", "in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a Graph and an", "n_single_matched_particles = 0, 0, 0, 0, 0, 0 for event in self.events: n_true_tracks", "candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks", "track candidates from event with matching criteria. Criteria given by ratios of common", "n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles,", "\"\"\" Loads files based on type \"\"\" file_type = self.__get_file_type() if file_type ==", "def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data):", "events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events,", "df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\" if", "def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits = {} assert \"x\"", "= nx.shortest_path(G) all_paths = {path: all_paths[path] for path in all_paths.keys() if path in", "\"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of", "\"edge_index\" in data.keys(), \"At least need a feature called edge_index, otherwise define default", "dict, \"Data must be a dictionary\" self.__process_data(data_dict) # Test if data is loaded", "\"\"\" def __init__(self, files): self.files = files self.event_data = None self.events = None", "Pytorch geometric files in file list \"\"\" # data = [] # for", "None # Test if files are loaded logging.info(\"Building events\") self.__build_events() assert self.events is", "single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs):", "Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self,", "ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits =", "end_key in all_paths[start_key].keys() if (start_key != end_key and end_key in ending_nodes)] hit_list =", "evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not", "= self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to be used in the", "Test if events are built def __len__(self): return len(self.events) def __getitem__(self, idx): event", "in the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise", "evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event with Intersection over", "<filename>onetrack/TrackingData.py # import all import os import sys import logging import numpy as", "== 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data):", "print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self,", "Returns all paths from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask", "= get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\":", "a single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check,", "elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return", "class Event(): \"\"\" An Event contains a Graph and an EventTruth object. It", "max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\",", "of Events, specifically for the tracking pipeline. An Event contains a Graph and", "candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph", "\"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\":", "hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids,", "if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut # Order", "\"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth =", "building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events):", "contains a Graph and an EventTruth object. \"\"\" def __init__(self, files): self.files =", "self.particles is not None assert self.hit_truth is not None # Define representation def", "self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else:", "of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\":", "= None self.events = None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data", "= None assert type(event_file) == str or type(event_file) == np.str_, \"Event file must", "assert self.events is not None # Test if events are built def __len__(self):", "r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges are", "__repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\",", "self.candidates = None self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to", "__matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from event with matching criteria.", "/ n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles:", "not None # Test if events are built def __len__(self): return len(self.events) def", "are the nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure", "type\") def __build_events(self): \"\"\" Builds Event objects from event data \"\"\" # self.events", "str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is", "ratios of common hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates", "'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise", "len(self.events) def __getitem__(self, idx): event = self.events[idx] return event def __load_files(self): \"\"\" Loads", "graph data \"\"\" self.graph_data = {k: data[k] for k in data.keys() - (self.hits.keys()", "of the detector, out_edges are the nodes towards the outer in_edges, out_edges =", "if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns edge", "candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID IS USED", "event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not", "n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation", "raise ValueError(\"Unknown data type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]}", "is not None assert self.hit_truth is not None # Define representation def __repr__(self):", "n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0, 0 for event", "\"At least need a feature called x, otherwise define default node feature in", "partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events):", "by increasing R r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2)", "process_map import networkx as nx from functools import partial from .tracking_utils import *", "building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs)", "= None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None # Test if", "\"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method,", "raise NotImplementedError(\"Plotting not implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs):", "numpy as np import pandas as pd import matplotlib.pyplot as plt import torch", "class EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth = None assert type(event_file)", "data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\"", "__init__(self, files): self.files = files self.event_data = None self.events = None self.evaluation =", "= data[key] def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data = {k:", "__build_events(self): \"\"\" Builds Event objects from event data \"\"\" # self.events = []", "__get_file_type(self): \"\"\" Determine type of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if", "sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph \"\"\" if building_method == \"CC\":", "__get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits = {} assert \"x\" in", "from event with Intersection over Union (IoU) \"\"\" raise NotImplementedError(\"IOU reconstruction not implemented", "raise ValueError(\"Could not find hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit", "to be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\"", "def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try: particle_filename = event_file +", "torch import torch.nn as nn import torch.nn.functional as F from scipy import sparse", "event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits = None", "n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\":", "score_cut # Order edges by increasing R r, phi, z = self.hits[\"x\"].T R", "candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class", "Event contains a Graph and an EventTruth object. It represents a unit of", "n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0, 0 for event in", "edge_mask = self.edges[\"scores\"] > score_cut # Order edges by increasing R r, phi,", "self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False,", "n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots", "pipeline. An Event contains a Graph and an EventTruth object. \"\"\" def __init__(self,", "= event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles", "\"\"\" A class that holds a list of Events, specifically for the tracking", "np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates = Candidates(hit_list, track_label_list,", "object. It represents a unit of particle physics data. \"\"\" def __init__(self, data):", "= self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut # Order edges by increasing", "yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation", "are the nodes towards the inner of the detector, out_edges are the nodes", "how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a", "assert \"edge_index\" in data.keys(), \"At least need a feature called edge_index, otherwise define", "loaded logging.info(\"Building events\") self.__build_events() assert self.events is not None # Test if events", "self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr", "\"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\":", "__get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges = {} assert \"edge_index\" in", "build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from event \"\"\" self.candidates =", "def __build_events(self): \"\"\" Builds Event objects from event data \"\"\" # self.events =", "otherwise define default node feature in config\" # Check if x is in", "files based on type \"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data", "the tracking pipeline. An Event contains a Graph and an EventTruth object. \"\"\"", "max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this", "Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\"", "= self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from", "NotImplementedError(\"Plotting not implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\"", "sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True)", "sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData():", "**kwargs): \"\"\" Builds connected components from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool()", "__plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates \"\"\" all_particles =", "data[k] for k in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False,", "raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits", "> 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] ==", "still more file types to be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch", "event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"]", "EventTruth object. It represents a unit of particle physics data. \"\"\" def __init__(self,", "None # Test if events are built def __len__(self): return len(self.events) def __getitem__(self,", "be used in the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph =", "/ n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\":", "evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\" if method ==", "self.__process_data(data_dict) # Test if data is loaded assert self.hits is not None assert", "n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks,", "partial from .tracking_utils import * from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads", "event with Intersection over Union (IoU) \"\"\" raise NotImplementedError(\"IOU reconstruction not implemented yet\")", "try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except:", "self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown", "# TODO: CHECK THAT HIT ID IS USED CORRECTLY!! return candidates class EventTruth():", "import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as", "n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks),", "in data.keys(), \"At least need a feature called edge_index, otherwise define default edge", "all_paths[start_key].keys() if (start_key != end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list", "\"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit", "path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in", "import torch import torch.nn as nn import torch.nn.functional as F from scipy import", "**kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles =", "= partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in", "n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method,", "Loads files based on type \"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\":", "self.graph_data is not None # Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\"", "candidates \"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method", "len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to be used in the pipeline", "__init__(self, data): self.graph = None self.event_truth = None self.candidates = None self.data =", "building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates =", "F from scipy import sparse as sps from tqdm import tqdm from tqdm.contrib.concurrent", "+= event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation =", "config\" # Check if edge_index is in data for key in data.keys(): if", "data): \"\"\" Processes data to be used in the pipeline \"\"\" if str(type(data))", "in config\" # Check if edge_index is in data for key in data.keys():", "assert self.hit_truth is not None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\"", "as nn import torch.nn.functional as F from scipy import sparse as sps from", "need a feature called edge_index, otherwise define default edge feature in config\" #", "idx): event = self.events[idx] return event def __load_files(self): \"\"\" Loads files based on", "type(event_file) == str or type(event_file) == np.str_, \"Event file must be a string\"", "event with matching criteria. Criteria given by ratios of common hits in candidates", "particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from", "def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building", "candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF", "for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self):", "of common hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates =", "= self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N", "\"\"\" Returns evaluation of candidates \"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles,", "**kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating", "# for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up!", "all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for", "a list of Events, specifically for the tracking pipeline. An Event contains a", "event def __load_files(self): \"\"\" Loads files based on type \"\"\" file_type = self.__get_file_type()", "edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut # Order edges by", "== data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns graph data", "in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine", "event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\" if method == \"matching\": self.evaluation", "self.event_truth = None self.candidates = None self.data = self.__process_data(data) def __process_data(self, data): \"\"\"", "\"Event file must be a string\" self.__process_data(event_file) # Test data loaded properly assert", "from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5,", "Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID IS USED CORRECTLY!! return", "__get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\" try: hit_truth_filename = event_file +", "0, 0, 0, 0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks +=", "None assert self.edges is not None assert self.graph_data is not None # Define", "# for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def", "candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles,", "raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns", "candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for", "must be a dictionary\" self.__process_data(data_dict) # Test if data is loaded assert self.hits", "in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G", "out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph", "np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by increasing R", "and an EventTruth object. \"\"\" def __init__(self, files): self.files = files self.event_data =", "for start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key != end_key and", "self.files = files self.event_data = None self.events = None self.evaluation = None logging.info(\"Loading", "x, otherwise define default node feature in config\" # Check if x is", "otherwise define default edge feature in config\" # Check if edge_index is in", "**kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation =", "not implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots", "# TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0,", "n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks", "plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a Graph and an EventTruth object.", "\"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self,", "as nx from functools import partial from .tracking_utils import * from .plotting_utils import", "hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method = building_method", "Test if files are loaded logging.info(\"Building events\") self.__build_events() assert self.events is not None", "def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\")", "Builds track candidates from graph \"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check,", "\"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs)", "num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates", "from tqdm.contrib.concurrent import process_map import networkx as nx from functools import partial from", "\"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\"", "track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID IS USED CORRECTLY!! return candidates", "out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for path in all_paths.keys() if", "data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\"", "\"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks", "hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates =", "file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return", "the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays", "\"\"\" # self.events = [] # for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events", "building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph \"\"\" if building_method ==", "paths from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"]", "Evaluates track candidates from event with Intersection over Union (IoU) \"\"\" raise NotImplementedError(\"IOU", "is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs)", "\"\"\" Returns particle data \"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles =", "== \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check,", "\"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\"", "truth data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth", "== \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\"", "is in data for key in data.keys(): if ( len(data[key].shape) > 1 and", "= { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles /", "**kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method,", "process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def", "n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def", "self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data =", "**kwargs): \"\"\" Evaluates track candidates from event with Intersection over Union (IoU) \"\"\"", "logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) #", "Returns edge data \"\"\" self.edges = {} assert \"edge_index\" in data.keys(), \"At least", "in data.keys(), \"At least need a feature called x, otherwise define default node", "np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort", "\"\"\" Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return", "return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe", "track candidates from graph \"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs)", "def __load_files(self): \"\"\" Loads files based on type \"\"\" file_type = self.__get_file_type() if", "= self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method", "def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\"", "components from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"]", "if files are loaded logging.info(\"Building events\") self.__build_events() assert self.events is not None #", "the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict())", "if ( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1", "raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise", "= sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self,", "**kwargs): \"\"\" Builds track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs)", "evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks,", "data \"\"\" self.edges = {} assert \"edge_index\" in data.keys(), \"At least need a", "self.event_data = None self.events = None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert", "assert type(event_file) == str or type(event_file) == np.str_, \"Event file must be a", "building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method,", "building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation =", "self.events, max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy", "== \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is not", "for end_key in all_paths[start_key].keys() if (start_key != end_key and end_key in ending_nodes)] hit_list", "= self.events[idx] return event def __load_files(self): \"\"\" Loads files based on type \"\"\"", "(\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method =", "sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs):", "edge_index, otherwise define default edge feature in config\" # Check if edge_index is", "nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for path in", "\"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from", "**kwargs): \"\"\" Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented", "return candidates class EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth = None", "Check if x is in data for key in data.keys(): if len(data[key]) ==", "valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key", "is not None assert self.edges is not None assert self.graph_data is not None", "= None self.event_truth = None self.candidates = None self.data = self.__process_data(data) def __process_data(self,", "'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is not a Pytorch", "self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file):", "class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids =", "\"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks /", "self.events, max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self,", "= files self.event_data = None self.events = None self.evaluation = None logging.info(\"Loading files\")", "self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids))", "and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method,", "Evaluates track candidates from event with matching criteria. Criteria given by ratios of", "pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data", "data \"\"\" self.hits = {} assert \"x\" in data.keys(), \"At least need a", "None self.candidates = None self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes data", "pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth", "def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph \"\"\" if", "score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph \"\"\" if sanity_check: edge_mask =", "file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs)", "= [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key !=", "\"\"\" Plots matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for", "physics data. \"\"\" def __init__(self, data): self.graph = None self.event_truth = None self.candidates", "from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] >", "{sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) #", "evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial =", "self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try: particle_filename = event_file", "all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key != end_key and end_key in ending_nodes)]", "raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from", "None self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to be used", "more file types to be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric", "= data[key] def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges = {}", "self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates", "event_file): \"\"\" Returns hit truth data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\"", "self.edges = None self.graph_data = None assert type(data_dict) == dict, \"Data must be", "not a Pytorch Geometric file\") except: raise ValueError(\"Unknown file type, there are still", "if x is in data for key in data.keys(): if len(data[key]) == len(data[\"x\"]):", "\"\"\" self.hits = {} assert \"x\" in data.keys(), \"At least need a feature", "return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds", "+ \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\") def", "self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check,", "\"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\")", "> R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes =", "torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file", "= pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth file\")", "files): self.files = files self.event_data = None self.events = None self.evaluation = None", "Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method,", "file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\" try: hit_truth_filename =", "event_file): self.particles = None self.hit_truth = None assert type(event_file) == str or type(event_file)", "as F from scipy import sparse as sps from tqdm import tqdm from", "all Pytorch geometric files in file list \"\"\" # data = [] #", "event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = {", "CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth =", "{} assert \"x\" in data.keys(), \"At least need a feature called x, otherwise", "track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates \"\"\"", "a feature called x, otherwise define default node feature in config\" # Check", "candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits", "= [] # for data in tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#,", "col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels,", "[len(path) for path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK", "1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks,", "file type\") def __build_events(self): \"\"\" Builds Event objects from event data \"\"\" #", "in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in all_paths[start_key].keys()", "tqdm(self.event_data): # self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type", "n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method", "[all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key != end_key", "try: particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not", "matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in", "Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check,", "edges are numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges", "are numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges =", "Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self,", "R r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges", "Test if data is loaded assert self.hits is not None assert self.edges is", "import os import sys import logging import numpy as np import pandas as", "Processes data to be used in the pipeline \"\"\" if type(data) == dict:", "None self.graph_data = None assert type(data_dict) == dict, \"Data must be a dictionary\"", "scipy import sparse as sps from tqdm import tqdm from tqdm.contrib.concurrent import process_map", "self.hits is not None assert self.edges is not None assert self.graph_data is not", "evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class that holds a", "Returns hit data \"\"\" self.hits = {} assert \"x\" in data.keys(), \"At least", "\"At least need a feature called edge_index, otherwise define default edge feature in", "# Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)}", "\"\"\" Loads all Pytorch geometric files in file list \"\"\" # data =", "building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building candidates with", "the nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges", "\"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track", "**kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method,", "data.event_file) else: raise ValueError(\"Unknown data type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])}", "\"\"\" Builds connected components from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else:", "= pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs): \"\"\"", "= [] # for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file,", "self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of file", "candidates from graph \"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif", "data): \"\"\" Returns hit data \"\"\" self.hits = {} assert \"x\" in data.keys(),", "self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates", "phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) # in_edges are the", "dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\"", "len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges", "in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data", "increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes", "\"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method ==", "by increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask]", "data.keys(), \"At least need a feature called x, otherwise define default node feature", "building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components", "data): \"\"\" Processes data to be used in the pipeline \"\"\" if type(data)", "self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to be used in", "= {} assert \"x\" in data.keys(), \"At least need a feature called x,", "directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\"", "for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"]", "return len(self.events) def __getitem__(self, idx): event = self.events[idx] return event def __load_files(self): \"\"\"", "Event(): \"\"\" An Event contains a Graph and an EventTruth object. It represents", "R = np.sqrt(r**2 + z**2) # in_edges are the nodes towards the inner", "building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph \"\"\"", "feature called x, otherwise define default node feature in config\" # Check if", "building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1", "define default node feature in config\" # Check if x is in data", "* from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric", "edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:,", "for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return", "print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\",", "from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file", "else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event objects from event", "file\") except: raise ValueError(\"Unknown file type, there are still more file types to", "def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data = {k: data[k] for", "to be used in the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph", "candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif", "+= event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method =", "is not a Pytorch Geometric file\") except: raise ValueError(\"Unknown file type, there are", "metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\" if self.evaluation is None:", "def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph \"\"\" if", "hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation = None def __repr__(self): return", "\"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi } return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track", "based on type \"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data =", "Event objects from event data \"\"\" # self.events = [] # for data", "self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file): \"\"\" Returns particle data \"\"\" try: particle_filename =", "self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for that method\") def", "observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for that method\") def __plot_matching_evaluation(self,", "== \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth,", "files are loaded logging.info(\"Building events\") self.__build_events() assert self.events is not None # Test", "file must be a string\" self.__process_data(event_file) # Test data loaded properly assert self.particles", "0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles +=", "data for key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key] = data[key] def", "elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates", "to be used in the pipeline \"\"\" if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data)", "for key in data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1]", "in all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys()", "if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented yet", "event data \"\"\" # self.events = [] # for data in tqdm(self.event_data): #", "__init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method =", "None assert type(event_file) == str or type(event_file) == np.str_, \"Event file must be", "is not None # Test if events are built def __len__(self): return len(self.events)", "numpy arrays if (type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy()", "hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise", "for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\"", "None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else:", "represents a unit of particle physics data. \"\"\" def __init__(self, data): self.graph =", "return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False,", "pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional", "+= event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks +=", "= np.sqrt(r**2 + z**2) # in_edges are the nodes towards the inner of", "__get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph \"\"\" if sanity_check:", "self.track_ids = track_ids self.building_method = building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()}", "in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays if (type(in_edges)", "nx.shortest_path(G) all_paths = {path: all_paths[path] for path in all_paths.keys() if path in starting_nodes}", "for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks,", "\"\"\" Evaluates track candidates from event with matching criteria. Criteria given by ratios", "self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could not find hit truth", "== str or type(event_file) == np.str_, \"Event file must be a string\" self.__process_data(event_file)", "ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from event", "candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False,", "event = self.events[idx] return event def __load_files(self): \"\"\" Loads files based on type", "n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0, 0, 0", "**kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\")", "logging import numpy as np import pandas as pd import matplotlib.pyplot as plt", "in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds", "hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\"", "Criteria given by ratios of common hits in candidates (\"reconstructed\") and particles (\"truth\")", "IS USED CORRECTLY!! return candidates class EventTruth(): def __init__(self, event_file): self.particles = None", "tqdm from tqdm.contrib.concurrent import process_map import networkx as nx from functools import partial", "= None self.graph_data = None assert type(data_dict) == dict, \"Data must be a", "max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from", "metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates \"\"\" all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles,", "file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data", "out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T)", "Graph and an EventTruth object. It represents a unit of particle physics data.", "{} assert \"edge_index\" in data.keys(), \"At least need a feature called edge_index, otherwise", "= np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates,", "= None self.hit_truth = None assert type(event_file) == str or type(event_file) == np.str_,", "n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks,", "not None assert self.edges is not None assert self.graph_data is not None #", "\"\"\" def __init__(self, data): self.graph = None self.event_truth = None self.candidates = None", "R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes =", "self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs): \"\"\" Returns evaluation", "== len(data[\"x\"]): self.hits[key] = data[key] def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\"", "__init__(self, data_dict): self.hits = None self.edges = None self.graph_data = None assert type(data_dict)", "else: edge_mask = self.edges[\"scores\"] > score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr =", "self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates", "def __init__(self, files): self.files = files self.event_data = None self.events = None self.evaluation", "starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G =", "ValueError(\"Unknown file type, this is not a Pytorch Geometric file\") except: raise ValueError(\"Unknown", "\"\"\" if building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\":", "n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks,", "import * def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file \"\"\" return", "data[key] def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\" self.graph_data = {k: data[k]", "is loaded assert self.hits is not None assert self.edges is not None assert", "if type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def", "N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return", "# Order edges by increasing R r, phi, z = self.hits[\"x\"].T R =", "data.keys(), \"At least need a feature called edge_index, otherwise define default edge feature", "pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns", "candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles /", "sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event \"\"\"", "not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from", "\"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\":", "if data is loaded assert self.hits is not None assert self.edges is not", "Plots evaluation of candidates \"\"\" if self.evaluation is None: raise ValueError(\"No evaluation available\")", "def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method,", "event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method", "raise ValueError(\"Unknown file type, there are still more file types to be added!\")", "\"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks:", "detector, out_edges are the nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask]", "def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\"", "\"\"\" Processes data to be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def", "nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are", "on type \"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files()", "len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to be used in the pipeline", "/ n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, }", "\"\"\" Returns edge data \"\"\" self.edges = {} assert \"edge_index\" in data.keys(), \"At", "data \"\"\" # self.events = [] # for data in tqdm(self.event_data): # self.events.append(Event(data))", "def evaluate_candidates(self, method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from event \"\"\" self.candidates.evaluate(method, self.event_truth,", "else: raise ValueError(\"Unknown data type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits,", "least need a feature called x, otherwise define default node feature in config\"", "!= np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by increasing", "of candidates \"\"\" if self.evaluation is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"]", "= self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(),", "track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation", "for the tracking pipeline. An Event contains a Graph and an EventTruth object.", "event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\":", "data is loaded assert self.hits is not None assert self.edges is not None", "Builds connected components from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask", "**kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def", "None assert type(data_dict) == dict, \"Data must be a dictionary\" self.__process_data(data_dict) # Test", "matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F", "self.event_data is not None # Test if files are loaded logging.info(\"Building events\") self.__build_events()", "specifically for the tracking pipeline. An Event contains a Graph and an EventTruth", "(type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort edges by", "0, 0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles", "candidates = self.__get_all_paths(sanity_check, **kwargs) elif building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise", "nn import torch.nn.functional as F from scipy import sparse as sps from tqdm", "G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for", "edges by increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask],", "evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event", "implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph", "file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return", "# import all import os import sys import logging import numpy as np", "\"\"\" if self.evaluation is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\":", "starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if", "nodes towards the inner of the detector, out_edges are the nodes towards the", "self.edges is not None assert self.graph_data is not None # Define representation def", "get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles", "self.hits = None self.edges = None self.graph_data = None assert type(data_dict) == dict,", "self.evaluation is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable,", "object. \"\"\" def __init__(self, files): self.files = files self.event_data = None self.events =", "EventTruth(): def __init__(self, event_file): self.particles = None self.hit_truth = None assert type(event_file) ==", "= Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates", "graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path]", "\"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8)", "= self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates", "tqdm import tqdm from tqdm.contrib.concurrent import process_map import networkx as nx from functools", "to be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in file", "None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None # Test if files", "data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key]", "N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels =", "def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event with Intersection over Union", "= torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown", "+= event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method,", "used in the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict", "= process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of file \"\"\" try:", "key in data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or", "max_workers=1) def __get_file_type(self): \"\"\" Determine type of file \"\"\" try: sample = torch.load(self.files[0],", "= EventTruth(event_file = data.event_file) else: raise ValueError(\"Unknown data type\") # Define representation def", "\"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks,", "\"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks /", "self.graph = None self.event_truth = None self.candidates = None self.data = self.__process_data(data) def", "event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\")", "n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles,", "# Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"])", "elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self,", "\"\"\" Plots evaluation of candidates \"\"\" if self.evaluation is None: raise ValueError(\"No evaluation", "\"\"\" Evaluates track candidates from event with Intersection over Union (IoU) \"\"\" raise", "there are still more file types to be added!\") def __load_pytorch_files(self): \"\"\" Loads", "/ n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\":", "Returns graph data \"\"\" self.graph_data = {k: data[k] for k in data.keys() -", "def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates from event with matching", "!= end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path)", "self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph \"\"\"", "/ n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\":", "data): self.graph = None self.event_truth = None self.candidates = None self.data = self.__process_data(data)", "= process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs)", "sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates =", "candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF", "= sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates", "{self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds", "available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting not implemented", "def __getitem__(self, idx): event = self.events[idx] return event def __load_files(self): \"\"\" Loads files", "an EventTruth object. \"\"\" def __init__(self, files): self.files = files self.event_data = None", "(type(in_edges) != np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy()", "valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID IS", "event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\": evaluation_method, \"eff\": n_matched_particles", "n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\",", "in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles,", "candidates from event with matching criteria. Criteria given by ratios of common hits", "= building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self):", "event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"] building_method = event.candidates.building_method self.evaluation = { \"building_method\": building_method, \"evaluation_method\":", "if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row, col", "NotImplementedError(\"KF candidates not implemented yet\") def __get_all_paths(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all", "event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events", "edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N, N))", "candidates from event with Intersection over Union (IoU) \"\"\" raise NotImplementedError(\"IOU reconstruction not", "def get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\":", "(start_key != end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)),", "process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of file \"\"\" try: sample", "start_key in all_paths.keys() for end_key in all_paths[start_key].keys() if (start_key != end_key and end_key", "data for key in data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1] ==", "import numpy as np import pandas as pd import matplotlib.pyplot as plt import", "hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to be", "Graph(): def __init__(self, data_dict): self.hits = None self.edges = None self.graph_data = None", "method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of candidates \"\"\"", "\"\"\" Processes data to be used in the pipeline \"\"\" if str(type(data)) ==", "import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as", "instance class TrackingData(): \"\"\" A class that holds a list of Events, specifically", "} print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def", "properly assert self.particles is not None assert self.hit_truth is not None # Define", "= {} assert \"edge_index\" in data.keys(), \"At least need a feature called edge_index,", "assert self.particles is not None assert self.hit_truth is not None # Define representation", "track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\")", "df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method, event_truth, **kwargs):", "for path in all_paths.keys() if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key", "all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for path in all_paths.keys() if path", "from functools import partial from .tracking_utils import * from .plotting_utils import * def", "find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth data \"\"\" try:", "be added!\") def __load_pytorch_files(self): \"\"\" Loads all Pytorch geometric files in file list", "def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method", "in data for key in data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1]", "\"\"\" return torch.load(file, map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return", "feature in config\" # Check if x is in data for key in", "implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching", "must be a string\" self.__process_data(event_file) # Test data loaded properly assert self.particles is", "class Graph(): def __init__(self, data_dict): self.hits = None self.edges = None self.graph_data =", "\"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self,", "building_method == \"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates =", "the nodes towards the inner of the detector, out_edges are the nodes towards", "None self.event_truth = None self.candidates = None self.data = self.__process_data(data) def __process_data(self, data):", "f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data", "__process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class", "(row.numpy(), col.numpy())), (N, N)) num_candidates, candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"],", "**kwargs): \"\"\" Returns evaluation of candidates \"\"\" if method == \"matching\": self.evaluation =", "len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids,", "in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths])", "self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"]", "Order edges by increasing R r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2", "score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph \"\"\" if sanity_check: edge_mask =", "import sparse as sps from tqdm import tqdm from tqdm.contrib.concurrent import process_map import", "np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges,", "__len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df =", "all import os import sys import logging import numpy as np import pandas", "* def load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file \"\"\" return torch.load(file,", "ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for path in valid_paths]) candidates", "# data = [] # for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data", "event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks += event.candidates.evaluation[\"n_duplicated_tracks\"]", "data to be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self, event_file):", "\"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True) return hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs):", "event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event contains a Graph and", "or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() # Sort edges", "ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric, observable, **kwargs) else: raise NotImplementedError(\"Plotting", "self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds Event", "\"CC\": candidates = self.__get_connected_components(sanity_check, **kwargs) elif building_method == \"AP\": candidates = self.__get_all_paths(sanity_check, **kwargs)", "= pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An", "end_key and end_key in ending_nodes)] hit_list = np.array(list(itertools.chain.from_iterable(valid_paths))) track_label_list = np.repeat(np.arange(len(valid_paths)), [len(path) for", "Events, specifically for the tracking pipeline. An Event contains a Graph and an", "raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\" Returns hit truth", "\"fr\": 1 - (n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, \"n_true_tracks\": n_true_tracks, \"n_reco_tracks\":", "this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0, 0,", "sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Returns all paths from graph \"\"\" if sanity_check: edge_mask", "else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs): \"\"\" Evaluates track candidates", "candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def evaluate(self, method,", "**kwargs): self.hit_ids = hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation = None", "geometric files in file list \"\"\" # data = [] # for file", "events\") self.__build_events() assert self.events is not None # Test if events are built", "in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT ID", "edge data \"\"\" self.edges = {} assert \"edge_index\" in data.keys(), \"At least need", "raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds", "Processes data to be used in the pipeline \"\"\" self.__get_particle_data(event_file) self.__get_hit_truth_data(event_file) def __get_particle_data(self,", "n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates,", "building_method == \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates", "for that method\") def __plot_matching_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs): \"\"\" Plots matching evaluation of", "data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def __get_graph_data(self, data): \"\"\" Returns graph data \"\"\"", "= None self.edges = None self.graph_data = None assert type(data_dict) == dict, \"Data", "**kwargs) class Graph(): def __init__(self, data_dict): self.hits = None self.edges = None self.graph_data", "sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events,", "Determine type of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) ==", "= None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def", "\"\"\" Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\")", "data[key] def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges = {} assert", "in the pipeline \"\"\" if str(type(data)) == \"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict =", "\"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise ValueError(\"Unknown file type\") def __build_events(self): \"\"\" Builds", "node feature in config\" # Check if x is in data for key", "> score_cut row, col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0)", "load_single_pytorch_file(file): \"\"\" Loads a single Pytorch Geometric file \"\"\" return torch.load(file, map_location=\"cpu\") def", "as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import", "not None assert self.hit_truth is not None # Define representation def __repr__(self): return", "data type\") # Define representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)}", "from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial,", "# event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks,", "\"<class 'torch_geometric.data.data.Data'>\": self.graph = Graph(data_dict = data.to_dict()) self.event_truth = EventTruth(event_file = data.event_file) else:", "self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns hit", "sanity_check=False, **kwargs): \"\"\" Builds track candidates from events \"\"\" logging.info(f\"Building candidates with sanity", "path in valid_paths]) candidates = Candidates(hit_list, track_label_list, building_method=\"AP\") # TODO: CHECK THAT HIT", "import process_map import networkx as nx from functools import partial from .tracking_utils import", "# data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\",", "Returns evaluation of candidates \"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth,", "= None assert type(data_dict) == dict, \"Data must be a dictionary\" self.__process_data(data_dict) #", "data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) ==", "\"x\" in data.keys(), \"At least need a feature called x, otherwise define default", "== \"KF\": candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates def", "\"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut #", "evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class that holds", "x is in data for key in data.keys(): if len(data[key]) == len(data[\"x\"]): self.hits[key]", "dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids}) return df def", "hit_truth class Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids", "type \"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else:", "evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial", "\"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks /", "be a string\" self.__process_data(event_file) # Test data loaded properly assert self.particles is not", "config\" # Check if x is in data for key in data.keys(): if", "pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\" An Event", "representation def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def", "== dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data):", "ValueError(\"Unknown file type, there are still more file types to be added!\") def", "evaluation_method, \"eff\": n_matched_particles / n_true_tracks, \"single_eff\": n_single_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks", "data \"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise", "if self.evaluation is None: raise ValueError(\"No evaluation available\") if self.evaluation[\"evaluation_method\"] == \"matching\": self.__plot_matching_evaluation(metric,", "if events are built def __len__(self): return len(self.events) def __getitem__(self, idx): event =", "all_particles = pd.concat([event.candidates.evaluation[\"particles\"].merge(event.event_truth.particles, on=\"particle_id\", how=\"inner\") for event in self.events]) plot_observable_performance(all_particles) class Event(): \"\"\"", "particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi) =", "instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class", "= None self.data = self.__process_data(data) def __process_data(self, data): \"\"\" Processes data to be", "# event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from", "type(data) == dict: self.__get_hit_data(data) self.__get_edge_data(data) self.__get_graph_data(data) else: raise ValueError(\"Unknown data type\") def __get_hit_data(self,", "not None # Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return", "event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\")", "import torch.nn as nn import torch.nn.functional as F from scipy import sparse as", "self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs)", "= event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename) self.hit_truth = self.__process_hit_truth(self.hit_truth) except: raise ValueError(\"Could", "\"\"\" Processes data to be used in the pipeline \"\"\" if type(data) ==", "__get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph \"\"\" if sanity_check:", "def __repr__(self): return f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self,", "in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles,", "return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data", "out_edges are the nodes towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] #", "f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self): \"\"\" Returns dataframe of", "CHECK THAT HIT ID IS USED CORRECTLY!! return candidates class EventTruth(): def __init__(self,", "\"\"\" file_type = self.__get_file_type() if file_type == \"pytorch_geometric\": self.event_data = self.__load_pytorch_files() else: raise", "dictionary\" self.__process_data(data_dict) # Test if data is loaded assert self.hits is not None", "Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def __get_kf_candidates(self, **kwargs): \"\"\" Builds KF candidates from", "# self.events.append(Event(data)) self.events = process_map(Event, self.event_data)#, max_workers=1) def __get_file_type(self): \"\"\" Determine type of", "np.unique(out_edges[~np.isin(out_edges, in_edges)]) # Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G)", "Returns particle data \"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename)", "def __len__(self): return len(self.events) def __getitem__(self, idx): event = self.events[idx] return event def", "hit truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"],", "representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file):", "if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\":", "data type\") def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits = {}", "are built def __len__(self): return len(self.events) def __getitem__(self, idx): event = self.events[idx] return", "n_true_tracks, \"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi", "map_location=\"cpu\") def build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance,", "evaluation of candidates \"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs)", "logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None # Test if files are", "are loaded logging.info(\"Building events\") self.__build_events() assert self.events is not None # Test if", "towards the outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy", "n_duplicated_tracks, n_matched_tracks_poi) = get_statistics(particles, candidates) evaluation = { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\":", "\"<class 'torch_geometric.data.data.Data'>\": return \"pytorch_geometric\" else: raise ValueError(\"Unknown file type, this is not a", "method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation", "TODO: CHECK THAT HIT ID IS USED CORRECTLY!! return candidates class EventTruth(): def", "of candidates \"\"\" if method == \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif", "assert self.event_data is not None # Test if files are loaded logging.info(\"Building events\")", "not None # Define representation def __repr__(self): return f\"Graph(hits={self.hits}, edges={self.edges}, graph_data={self.graph_data})\" def __len__(self):", "wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges,", "n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles += event.candidates.evaluation[\"n_single_matched_particles\"] n_matched_tracks += event.candidates.evaluation[\"n_matched_tracks\"] n_duplicated_tracks", "= pd.read_csv(particle_filename) except: raise ValueError(\"Could not find particles file\") def __get_hit_truth_data(self, event_file): \"\"\"", "track candidates from events \"\"\" logging.info(\"Evaluating candidates\") evaluate_single_candidates_partial = partial(evaluate_single_candidates, evaluation_method=evaluation_method, **kwargs) self.events", "if path in starting_nodes} valid_paths = [all_paths[start_key][end_key] for start_key in all_paths.keys() for end_key", "increasing R r, phi, z = self.hits[\"x\"].T R = np.sqrt(r**2 + z**2) #", "= {k: data[k] for k in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self,", "nx from functools import partial from .tracking_utils import * from .plotting_utils import *", "**kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\"", "\"\"\" try: particle_filename = event_file + \"-particles.csv\" self.particles = pd.read_csv(particle_filename) except: raise ValueError(\"Could", "\"\"\" # data = [] # for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\"))", "hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks, n_matched_tracks_poi)", "from .tracking_utils import * from .plotting_utils import * def load_single_pytorch_file(file): \"\"\" Loads a", "sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return", "process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track", "def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to be used", "# Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths =", "in tqdm(self.events): # event.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track", "# Define representation def __repr__(self): return f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def", "hit data \"\"\" self.hits = {} assert \"x\" in data.keys(), \"At least need", "n_reco_tracks: {n_reco_tracks}, n_matched_particles: {n_matched_particles}, n_matched_tracks: {n_matched_tracks}, n_duplicated_tracks: {n_duplicated_tracks}\") def plot_evaluation(self, metric=\"eff\", observable=\"eta\", **kwargs):", "outer in_edges, out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays if", "raise ValueError(\"Unknown file type, this is not a Pytorch Geometric file\") except: raise", "\"\"\" Returns graph data \"\"\" self.graph_data = {k: data[k] for k in data.keys()", "graph_data={self.graph_data})\" def __len__(self): return len(self.hits[\"x\"]) def __process_data(self, data): \"\"\" Processes data to be", "self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits = None self.edges = None", "class TrackingData(): \"\"\" A class that holds a list of Events, specifically for", "# Sort edges by increasing R wrong_direction_mask = R[in_edges] > R[out_edges] in_edges[wrong_direction_mask], out_edges[wrong_direction_mask]", "= partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event", "that holds a list of Events, specifically for the tracking pipeline. An Event", "sanity_check: edge_mask = self.edges[\"y\"].bool() else: edge_mask = self.edges[\"scores\"] > score_cut row, col =", "candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from event", "candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events =", "**kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): # event.evaluate_candidates(evaluation_method,", "type(event_file) == np.str_, \"Event file must be a string\" self.__process_data(event_file) # Test data", "sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): #", "data): \"\"\" Returns edge data \"\"\" self.edges = {} assert \"edge_index\" in data.keys(),", "Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks, n_duplicated_tracks, n_single_matched_particles = 0, 0, 0,", "match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs) (n_true_tracks, n_reco_tracks, n_matched_particles, n_single_matched_particles, n_matched_tracks, n_duplicated_tracks,", "\"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs)", "( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and", "tracking pipeline. An Event contains a Graph and an EventTruth object. \"\"\" def", "from events \"\"\" logging.info(f\"Building candidates with sanity check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method,", "type of file \"\"\" try: sample = torch.load(self.files[0], map_location=\"cpu\") if str(type(sample)) == \"<class", "build_single_candidates(instance, building_method, sanity_check, **kwargs): instance.build_candidates(building_method, sanity_check, **kwargs) return instance def evaluate_single_candidates(instance, evaluation_method, **kwargs):", "in_edges are the nodes towards the inner of the detector, out_edges are the", "else: raise ValueError(\"Unknown data type\") def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\"", "for k in data.keys() - (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs):", "__len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to be used in", "particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth, particles, build_method = self.building_method, **kwargs)", "tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks, n_matched_particles, n_matched_tracks,", "\"\"\" Builds track candidates from graph \"\"\" if building_method == \"CC\": candidates =", "in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"] n_matched_particles += event.candidates.evaluation[\"n_matched_particles\"] n_single_matched_particles +=", "self.building_method = building_method self.evaluation = None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def", "**kwargs): \"\"\" Returns all paths from graph \"\"\" if sanity_check: edge_mask = self.edges[\"y\"].bool()", "\"n_reco_tracks\": n_reco_tracks, \"n_matched_particles\": n_matched_particles, \"n_single_matched_particles\": n_single_matched_particles, \"n_matched_tracks\": n_matched_tracks, \"n_duplicated_tracks\": n_duplicated_tracks, \"n_matched_tracks_poi\": n_matched_tracks_poi }", "is not None # Test if files are loaded logging.info(\"Building events\") self.__build_events() assert", "or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] = data[key] def", "self.hit_truth = None assert type(event_file) == str or type(event_file) == np.str_, \"Event file", "get_df(self): \"\"\" Returns dataframe of candidates \"\"\" df = pd.DataFrame({\"hit_id\": self.hit_ids, \"track_id\": self.track_ids})", "**kwargs): \"\"\" Evaluates track candidates from event with matching criteria. Criteria given by", "== data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key] =", "check: {sanity_check}\") build_single_candidates_partial = partial(build_single_candidates, building_method=building_method, sanity_check=sanity_check, **kwargs) self.events = process_map(build_single_candidates_partial, self.events, max_workers=8)", "observable=\"eta\", **kwargs): \"\"\" Plots evaluation of candidates \"\"\" if self.evaluation is None: raise", "Returns hit truth data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth =", "torch.nn as nn import torch.nn.functional as F from scipy import sparse as sps", "edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())), (N,", "data): \"\"\" Returns graph data \"\"\" self.graph_data = {k: data[k] for k in", "feature in config\" # Check if edge_index is in data for key in", "\"\"\" self.graph_data = {k: data[k] for k in data.keys() - (self.hits.keys() & self.edges.keys())}", "loaded properly assert self.particles is not None assert self.hit_truth is not None #", "G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path: all_paths[path] for path in all_paths.keys()", "Builds track candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self,", "data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape) == 1 and data[key].shape[0] == data[\"edge_index\"].shape[1] ): self.edges[key]", "def __get_edge_data(self, data): \"\"\" Returns edge data \"\"\" self.edges = {} assert \"edge_index\"", "be a dictionary\" self.__process_data(data_dict) # Test if data is loaded assert self.hits is", "map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#, max_workers=1) return data def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs):", "& self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph", "Candidates(): def __init__(self, hit_ids, track_ids, building_method, **kwargs): self.hit_ids = hit_ids self.track_ids = track_ids", "Build graph G = nx.DiGraph() G.add_edges_from(np.stack([in_edges, out_edges]).T) all_paths = nx.shortest_path(G) all_paths = {path:", "!= np.ndarray) or (type(out_edges) != np.ndarray): in_edges = in_edges.numpy() out_edges = out_edges.numpy() #", "**kwargs) else: raise NotImplementedError(\"Plotting not implemented yet for that method\") def __plot_matching_evaluation(self, metric=\"eff\",", "logging.info(\"Building events\") self.__build_events() assert self.events is not None # Test if events are", "hit truth data \"\"\" try: hit_truth_filename = event_file + \"-truth.csv\" self.hit_truth = pd.read_csv(hit_truth_filename)", "event in tqdm(self.events): # event.evaluate_candidates(evaluation_method, **kwargs) # TODO: Tidy this up! n_true_tracks, n_reco_tracks,", "sanity_check, **kwargs) def evaluate_candidates(self, evaluation_method=\"matching\", **kwargs): \"\"\" Evaluates track candidates from events \"\"\"", "method, event_truth, **kwargs): \"\"\" Returns evaluation of candidates \"\"\" if method == \"matching\":", "Builds KF candidates from graph \"\"\" raise NotImplementedError(\"KF candidates not implemented yet\") def", "candidates from event \"\"\" self.candidates = self.graph.build_candidates(building_method, sanity_check, **kwargs) def evaluate_candidates(self, method=\"matching\", **kwargs):", "particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\": 1 - (n_matched_tracks / n_reco_tracks),", "list of Events, specifically for the tracking pipeline. An Event contains a Graph", "def evaluate_single_candidates(instance, evaluation_method, **kwargs): instance.evaluate_candidates(**kwargs) return instance class TrackingData(): \"\"\" A class that", "event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates", "files\") self.__load_files() assert self.event_data is not None # Test if files are loaded", "col = self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr,", "== \"matching\": self.evaluation = self.__matching_reconstruction(event_truth.particles, event_truth.hit_truth, **kwargs) elif method == \"iou\": self.evaluation =", "out_edges = self.edges[\"edge_index\"][:, edge_mask] # Ensure edges are numpy arrays if (type(in_edges) !=", "0, 0, 0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"] n_reco_tracks += event.candidates.evaluation[\"n_reco_tracks\"]", "= { \"evaluation_method\": \"matching\", \"particles\": particles, \"candidates\": candidates, \"eff\": n_matched_particles / n_true_tracks, \"fr\":", "edge_index is in data for key in data.keys(): if ( len(data[key].shape) > 1", "self.candidates.evaluate(method, self.event_truth, **kwargs) class Graph(): def __init__(self, data_dict): self.hits = None self.edges =", "files self.event_data = None self.events = None self.evaluation = None logging.info(\"Loading files\") self.__load_files()", "import all import os import sys import logging import numpy as np import", "import partial from .tracking_utils import * from .plotting_utils import * def load_single_pytorch_file(file): \"\"\"", "method\") return candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from", "[] # for file in tqdm(self.files): # data.append(torch.load(file, map_location=\"cpu\")) data = process_map(load_single_pytorch_file, self.files)#,", "\"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles, hit_truth, **kwargs):", "type, this is not a Pytorch Geometric file\") except: raise ValueError(\"Unknown file type,", "default node feature in config\" # Check if x is in data for", "candidate_labels = sps.csgraph.connected_components(sparse_edges, directed=False, return_labels=True) candidates = Candidates(self.hits[\"hid\"], candidate_labels, building_method=\"CC\") return candidates def", "candidates def __get_connected_components(self, sanity_check=False, score_cut=0.5, **kwargs): \"\"\" Builds connected components from graph \"\"\"", "Event contains a Graph and an EventTruth object. \"\"\" def __init__(self, files): self.files", "assert self.hits is not None assert self.edges is not None assert self.graph_data is", "candidates = self.__get_kf_candidates(**kwargs) else: raise ValueError(\"Unknown building method\") return candidates def __get_connected_components(self, sanity_check=False,", "- (self.hits.keys() & self.edges.keys())} def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates", "hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\" particles, candidates = match_reco_tracks(self.get_df(), hit_truth,", "assert self.edges is not None assert self.graph_data is not None # Define representation", "None self.evaluation = None logging.info(\"Loading files\") self.__load_files() assert self.event_data is not None #", "self.hit_ids = hit_ids self.track_ids = track_ids self.building_method = building_method self.evaluation = None def", "self.edges[\"edge_index\"][:, edge_mask] edge_attr = np.ones(row.size(0)) N = self.hits[\"x\"].size(0) sparse_edges = sps.coo_matrix((edge_attr, (row.numpy(), col.numpy())),", "evaluation_method=evaluation_method, **kwargs) self.events = process_map(evaluate_single_candidates_partial, self.events, max_workers=8) # for event in tqdm(self.events): #", "An Event contains a Graph and an EventTruth object. \"\"\" def __init__(self, files):", "in data.keys(): if ( len(data[key].shape) > 1 and data[key].shape[1] == data[\"edge_index\"].shape[1] or len(data[key].shape)", "self.__process_data(event_file) # Test data loaded properly assert self.particles is not None assert self.hit_truth", "given by ratios of common hits in candidates (\"reconstructed\") and particles (\"truth\") \"\"\"", "from tqdm import tqdm from tqdm.contrib.concurrent import process_map import networkx as nx from", "truth file\") def __process_hit_truth(self, hit_truth): \"\"\" Processes hit truth data \"\"\" hit_truth.drop_duplicates(subset=[\"hit_id\"], inplace=True)", "__process_data(self, data): \"\"\" Processes data to be used in the pipeline \"\"\" if", "def __process_data(self, data): \"\"\" Processes data to be used in the pipeline \"\"\"", "f\"Event(graph=({len(self.graph.hits['x'])} hits, {self.graph.edges['edge_index'].shape[1]} edges), event_truth=({len(self.event_truth)} particles), candidates=({len(self.candidates)} candidates))\" def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs):", "0, 0, 0, 0, 0, 0 for event in self.events: n_true_tracks += event.candidates.evaluation[\"n_true_tracks\"]", "type\") def __get_hit_data(self, data): \"\"\" Returns hit data \"\"\" self.hits = {} assert", "data_dict): self.hits = None self.edges = None self.graph_data = None assert type(data_dict) ==", "return evaluation def __iou_reconstruction(self, **kwargs): \"\"\" Evaluates track candidates from event with Intersection", "contains a Graph and an EventTruth object. It represents a unit of particle", "None self.hit_truth = None assert type(event_file) == str or type(event_file) == np.str_, \"Event", "def build_candidates(self, building_method=\"CC\", sanity_check=False, **kwargs): \"\"\" Builds track candidates from graph \"\"\" if", "f\"EventTruth(particles={self.particles}, hit_truth={self.hit_truth})\" def __len__(self): return len(self.particles) def __process_data(self, event_file): \"\"\" Processes data to", "(n_matched_tracks / n_reco_tracks), \"dup\": n_duplicated_tracks / n_reco_tracks, } print(self.evaluation) print(f\"n_true_tracks: {n_true_tracks}, n_reco_tracks: {n_reco_tracks},", "# Test data loaded properly assert self.particles is not None assert self.hit_truth is", "in_edges[wrong_direction_mask], out_edges[wrong_direction_mask] = out_edges[wrong_direction_mask], in_edges[wrong_direction_mask] starting_nodes = np.unique(in_edges[~np.isin(in_edges, out_edges)]) ending_nodes = np.unique(out_edges[~np.isin(out_edges, in_edges)])", "None def __repr__(self): return f\"{self.__len__()} Candidates(hit_ids={self.hit_ids}, track_ids={self.track_ids})\" def __len__(self): return len(np.unique(self.track_ids)) def get_df(self):", "method == \"iou\": self.evaluation = self.__iou_reconstruction(**kwargs) else: raise ValueError(\"Unknown method\") def __matching_reconstruction(self, particles," ]
[ "text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]: return Todo.query.all() def", "Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed = True db.session.commit()", "True db.session.commit() return todo def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if", "Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str, completed: bool)", "completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text", "db from todo_api.models import Todo def create_todo(text: str, user_id: int) -> Todo: todo", "from todo_api.extensions import db from todo_api.models import Todo def create_todo(text: str, user_id: int)", "Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]: todo", "from typing import List, Optional from todo_api.extensions import db from todo_api.models import Todo", "Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed = True db.session.commit() return todo def", "return todo def update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]: todo =", "Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() ->", "return None todo.text = text todo.completed = completed db.session.commit() return todo def complete_todo(public_id:", "Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id:", "= completed db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first()", "= Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed = True db.session.commit() return todo", "uuid from typing import List, Optional from todo_api.extensions import db from todo_api.models import", "= Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]:", "-> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit() return", "-> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos()", "Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]: return Todo.query.all()", "import db from todo_api.models import Todo def create_todo(text: str, user_id: int) -> Todo:", "List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo", "def update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if", "return todo def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo:", "todo def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return", "update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not", "get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first()", "str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str,", "None todo.text = text todo.completed = completed db.session.commit() return todo def complete_todo(public_id: str)", "todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit() return True def", "Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text = text todo.completed = completed db.session.commit()", "todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed = True db.session.commit() return", "-> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str, completed:", "Todo def create_todo(text: str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id)", "not todo: return None todo.completed = True db.session.commit() return todo def delete_todo(public_id: str)", "completed db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if", "-> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed = True", "return False db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int: todos_deleted = Todo.query.delete()", "todo def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo", "Optional from todo_api.extensions import db from todo_api.models import Todo def create_todo(text: str, user_id:", "todo.completed = completed db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]: todo =", "Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text = text todo.completed", "List, Optional from todo_api.extensions import db from todo_api.models import Todo def create_todo(text: str,", "todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text = text todo.completed =", "import List, Optional from todo_api.extensions import db from todo_api.models import Todo def create_todo(text:", "user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id:", "= text todo.completed = completed db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]:", "todo def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return", "db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int: todos_deleted = Todo.query.delete() db.session.commit() return", "Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit() return True def delete_all_todos() ->", "todo.text = text todo.completed = completed db.session.commit() return todo def complete_todo(public_id: str) ->", "not todo: return None todo.text = text todo.completed = completed db.session.commit() return todo", "db.session.commit() return True def delete_all_todos() -> int: todos_deleted = Todo.query.delete() db.session.commit() return todos_deleted", "int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def", "def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str,", "False db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int: todos_deleted = Todo.query.delete() db.session.commit()", "= True db.session.commit() return todo def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first()", "text todo.completed = completed db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]: todo", "def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo =", "db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str)", "todo: return None todo.text = text todo.completed = completed db.session.commit() return todo def", "db.session.commit() return todo def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not", "return todo def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]:", "db.session.commit() return todo def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not", "create_todo(text: str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit()", "not todo: return False db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int: todos_deleted", "def delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False", "if not todo: return None todo.text = text todo.completed = completed db.session.commit() return", "str, text: str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo:", "todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text: str, completed: bool) ->", "str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit()", "return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def", "if not todo: return None todo.completed = True db.session.commit() return todo def delete_todo(public_id:", "bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit() return True", "from todo_api.models import Todo def create_todo(text: str, user_id: int) -> Todo: todo =", "if not todo: return False db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int:", "todo: return None todo.completed = True db.session.commit() return todo def delete_todo(public_id: str) ->", "str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None", "-> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return", "todo_api.extensions import db from todo_api.models import Todo def create_todo(text: str, user_id: int) ->", "= Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo) db.session.commit() return True def delete_all_todos()", "import Todo def create_todo(text: str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text,", "todo def update_todo(public_id: str, text: str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first()", "complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed", "import uuid from typing import List, Optional from todo_api.extensions import db from todo_api.models", "= Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text = text todo.completed = completed", "def create_todo(text: str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo)", "-> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text = text", "return None todo.completed = True db.session.commit() return todo def delete_todo(public_id: str) -> bool:", "db.session.commit() return todo def get_all_todos() -> List[Todo]: return Todo.query.all() def get_todo_by_public_id(public_id: str) ->", "def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None", "todo_api.models import Todo def create_todo(text: str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(),", "text: str, completed: bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return", "return todo def complete_todo(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo:", "todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]:", "todo.completed = True db.session.commit() return todo def delete_todo(public_id: str) -> bool: todo =", "todo: return False db.session.delete(todo) db.session.commit() return True def delete_all_todos() -> int: todos_deleted =", "typing import List, Optional from todo_api.extensions import db from todo_api.models import Todo def", "str, user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return", "None todo.completed = True db.session.commit() return todo def delete_todo(public_id: str) -> bool: todo", "user_id: int) -> Todo: todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo", "str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.completed =", "get_todo_by_public_id(public_id: str) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() return todo def update_todo(public_id: str, text:", "delete_todo(public_id: str) -> bool: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return False db.session.delete(todo)", "= Todo(public_id=uuid.uuid4(), text=text, user_id=user_id) db.session.add(todo) db.session.commit() return todo def get_all_todos() -> List[Todo]: return", "bool) -> Optional[Todo]: todo = Todo.query.filter_by(public_id=public_id).first() if not todo: return None todo.text =" ]
[ "from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin,", "for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline):", "ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as base class because of MRO", "Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin", "pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used", "class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as", "''' Import modules to register class names in global registry Define convenience classes", "NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass", "RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class", "'<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer,", "in global registry Define convenience classes composed of different mixins ''' __author__ =", "from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for", "NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to", "initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as base class", ".base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\", "convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): #", "global registry Define convenience classes composed of different mixins ''' __author__ = '<NAME>'", "be used as base class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline):", "class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be", "__author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import", "names in global registry Define convenience classes composed of different mixins ''' __author__", "of different mixins ''' __author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence,", "Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline,", "convenience classes composed of different mixins ''' __author__ = '<NAME>' from .base_pipeline import", "''' __author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins", "to be used as base class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin,", "AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin #", "pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as base class because", "class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as base class because of", "as base class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs", "different mixins ''' __author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence", "Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class", "to register class names in global registry Define convenience classes composed of different", "modules to register class names in global registry Define convenience classes composed of", "import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class", "NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be", "ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as base", "registry Define convenience classes composed of different mixins ''' __author__ = '<NAME>' from", "DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin", "# Needs to be used as base class because of MRO initialization pass", "<reponame>ptoman/SimpleML ''' Import modules to register class names in global registry Define convenience", "MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as base", "RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as base class because of MRO", "Import modules to register class names in global registry Define convenience classes composed", "SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin):", "because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used", "= '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split,", ".validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience", "used as base class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): #", "of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to be used as", "class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as base class because of", "import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin,", "ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline,", "register class names in global registry Define convenience classes composed of different mixins", "Pipeline): # Needs to be used as base class because of MRO initialization", "composed of different mixins ''' __author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline,", "class names in global registry Define convenience classes composed of different mixins '''", "ExplicitSplitMixin # Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin):", "class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs", "mixins ''' __author__ = '<NAME>' from .base_pipeline import Pipeline, AbstractPipeline, DatasetSequence, TransformedSequence from", "Needs to be used as base class because of MRO initialization pass class", "pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as base class because", "# Mixin implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass", "ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin, Pipeline): # Needs to be used as base class", "classes composed of different mixins ''' __author__ = '<NAME>' from .base_pipeline import Pipeline,", "implementations for convenience class NoSplitPipeline(Pipeline, NoSplitMixin): pass class ExplicitSplitPipeline(Pipeline, ExplicitSplitMixin): pass class RandomSplitPipeline(RandomSplitMixin,", "TransformedSequence from .validation_split_mixins import Split, SplitContainer, NoSplitMixin, RandomSplitMixin,\\ ChronologicalSplitMixin, ExplicitSplitMixin # Mixin implementations", "Define convenience classes composed of different mixins ''' __author__ = '<NAME>' from .base_pipeline", "base class because of MRO initialization pass class ChronologicalSplitPipeline(ChronologicalSplitMixin, Pipeline): # Needs to" ]
[ "\"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are", "for mtype in mtypes: for dim in dims: for dtype in dtypes: print(\"\")", "matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype))", "the data-type to use (float16, float32 or float64) :param n_iterable: The n-values to", "dims: The dimensions to use. :param dtypes: The dtype-values to use. :return: Nothing.", "matrices \"\"\" if self.l is None or self.u is None: self.l, self.u =", "= LU) :return: A Tuple l,u of matrices \"\"\" if self.l is None", "the equation Ax=b for x and the matrix A. :param b: The vector", "dim if dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are", "M: \" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M)", "n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described.", "to use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not in", "n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\"", "1): result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result) def", "mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\")", "Calculates the matrix from the values given to the constructor and its inverse.", "\"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype = dtype", "are 'hilbert' and 'saite'.\") self.mtype = mtype if dim <= 0: raise Exception(\"dim", "and the matrix A. :param b: The vector b to solve the Matrix", "plot class Matrix: \"\"\" Provides Methods for operations with an hilbert- or a", "(Matrix A = LU) :return: A Tuple l,u of matrices \"\"\" if self.l", "row - 1 == col or col - 1 == row: arr[row].append(-1) else:", "to use (float16, float32 or float64) :param n: The dimension to use. :return:", "def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described in", "must be > 0\") self.dim = dim if dtype not in [\"float16\", \"float32\",", "numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of the", "{0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as", "its inverse. :return: Nothing. \"\"\" arr = [] if self.mtype == \"saite\": for", "dtype-values to use. :return: Nothing. \"\"\" for mtype in mtypes: for dim in", "in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\")", "i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None,", "dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor = None", "from Ax=b. \"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x", "x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described in 3.1B. :param", "i to use :param dtype: the data-type to use (float16, float32 or float64)", "data-type to use (float16, float32 or float64) :param n: The dimension to use.", "= scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of the matrix. :return: The", ":return: The vector x from Ax=b. \"\"\" l, u = self.lu() x =", "\" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) =", "\"\"\" Executes experiments as described in 3.2B B. (Hilbert) :param i_max: The maximum", "\"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u,", "self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b): \"\"\" Solves", "dim in dims: for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype,", "for dim in dims: for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1},", "None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the", "The n-values to use. :param i_iterable: The i-values to use. (if i>n it", "in i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None,", "experiment == \"3.2B - A\": for n in n_iterable: main_32b_saite(n) elif experiment ==", "\"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes the class instance. :param mtype:", "\"float32\" or \"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype.", "plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described in 3.2B B.", "return self.l, self.u def solve(self, b): \"\"\" Solves the equation Ax=b for x", "the matrix. :return: The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) *", "in 3.1B. :param mtypes: The mtype-values to use. :param dims: The dimensions to", "to use. :param dtypes: The dtype-values to use. :return: Nothing. \"\"\" for mtype", "Matrix for. :return: The vector x from Ax=b. \"\"\" l, u = self.lu()", "Nothing. \"\"\" for dtype in dtypes: for n in n_iterable: for i_max in", "n_iterable: The n-values to use. :param i_iterable: The i-values to use. (if i>n", "'hilbert' and 'saite'.\") self.mtype = mtype if dim <= 0: raise Exception(\"dim must", "u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False)", "A Tuple l,u of matrices \"\"\" if self.l is None or self.u is", "numpy.identity(n, dtype=dtype) for i in xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix)", "as described in 3.2B :param dtypes: the data-type to use (float16, float32 or", ":param dtypes: the data-type to use (float16, float32 or float64) :param n_iterable: The", "(numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate", "\"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype =", "dim <= 0: raise Exception(\"dim must be > 0\") self.dim = dim if", "in 3.2B B. (Hilbert) :param i_max: The maximum i to use :param dtype:", "\"\"\" Initializes the class instance. :param mtype: The matrix type (\"hilbert\" or \"saite\"", "print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described in 3.2B :param", "x, lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described", "3.1B. :param mtypes: The mtype-values to use. :param dims: The dimensions to use.", "scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims,", "instance. :param mtype: The matrix type (\"hilbert\" or \"saite\" for triangular) :param dim:", "i-values to use. (if i>n it will be ignored). :return: Nothing. \"\"\" for", "A. :param b: The vector b to solve the Matrix for. :return: The", "use. (if i>n it will be ignored). :return: Nothing. \"\"\" for dtype in", "main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes, n_iterable, i_iterable) else: print(\"Unknown experiment\")", "for row in xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim): if row", "dtype): \"\"\" Initializes the class instance. :param mtype: The matrix type (\"hilbert\" or", "Methods for operations with an hilbert- or a special triangular matrix. \"\"\" def", "# Authors: <NAME> (lambertt) and <NAME> (odafaluy) import numpy import scipy import scipy.linalg", "dtype)) result = numpy.identity(n, dtype=dtype) for i in xrange(1, i_max + 1): result", "it will be ignored). :return: Nothing. \"\"\" for dtype in dtypes: for n", "given to the constructor and its inverse. :return: Nothing. \"\"\" arr = []", "mtypes: The mtype-values to use. :param dims: The dimensions to use. :param dtypes:", "i_iterable): \"\"\" Executes experiments as described in 3.2B :param dtypes: the data-type to", "to use. :return: Nothing. \"\"\" for mtype in mtypes: for dim in dims:", "x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x def", "The type to use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype", "in dtypes: for n in n_iterable: for i_max in i_iterable: if i_max >", ":return: A Tuple l,u of matrices \"\"\" if self.l is None or self.u", "\"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix", "The i-values to use. (if i>n it will be ignored). :return: Nothing. \"\"\"", "col - 1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr", "== \"3.2B - A\": for n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B", "print(\"cond(M) = {1} || I - M M^(-1) || = {0}\".format(condition, matrix.condition())) def", "dim, dtype): \"\"\" Initializes the class instance. :param mtype: The matrix type (\"hilbert\"", "and its inverse. :return: Nothing. \"\"\" arr = [] if self.mtype == \"saite\":", "elif experiment == \"3.2B - A\": for n in n_iterable: main_32b_saite(n) elif experiment", "matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the", "ord=numpy.inf) print(\"cond(M) = {1} || I - M M^(-1) || = {0}\".format(condition, matrix.condition()))", "(float16, float32 or float64) :param n: The dimension to use. :return: Nothing. \"\"\"", "i_max: The maximum i to use :param dtype: the data-type to use (float16,", "= None self.l = None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates", "self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values", "return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described in 3.1B.", "B. (Hilbert) :param i_max: The maximum i to use :param dtype: the data-type", "type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i in xrange(1, i_max +", "row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix =", "scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b): \"\"\" Solves the equation Ax=b", "\"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B - A\": for n in", "== col: arr[row].append(2) elif row - 1 == col or col - 1", "of matrices \"\"\" if self.l is None or self.u is None: self.l, self.u", "numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable):", "> 0. :param dtype: The type to use. Can be \"float16\", \"float32\" or", "See start.py for more information. :return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes,", "of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\"", ":param mtype: The matrix type (\"hilbert\" or \"saite\" for triangular) :param dim: The", "m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError)", "{1} || I - M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n)", "\"saite\": for row in xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim): if", "= {1} || I - M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n):", "= scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates", ":param dim: The dimension. Must be > 0. :param dtype: The type to", "\"\"\" Executes experiments as described. See start.py for more information. :return: Nothing. \"\"\"", "* numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I - M M^(-1) || =", "+ ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1}", "\"3.2B - A\": for n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B -", "for n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes, n_iterable,", "= None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values given", "1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist()", "if self.mtype == \"saite\": for row in xrange(0, self.dim): arr.append([]) for col in", "return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into", "def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values given to the constructor", "ex: print(\"Cannot calculate inverse of M: \" + ex.message) continue condition = numpy.linalg.norm(m,", "the constructor and its inverse. :return: Nothing. \"\"\" arr = [] if self.mtype", "condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self):", "or \"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed", "triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes the class instance.", "for n in n_iterable: for i_max in i_iterable: if i_max > n: continue", "\"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert'", "if self.l is None or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True)", "\"\"\" Solves the equation Ax=b for x and the matrix A. :param b:", "lower) and u (right upper) matrices. (Matrix A = LU) :return: A Tuple", "be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise", "inverse of M: \" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv,", "in dims: for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim,", "the class instance. :param mtype: The matrix type (\"hilbert\" or \"saite\" for triangular)", "0. :param dtype: The type to use. Can be \"float16\", \"float32\" or \"flaot64\"", "class Matrix: \"\"\" Provides Methods for operations with an hilbert- or a special", "matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\"", "- (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot", "into l (left lower) and u (right upper) matrices. (Matrix A = LU)", "numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv))", "x = scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes", "= scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes,", "to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with", "if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B - A\":", "l,u of matrices \"\"\" if self.l is None or self.u is None: self.l,", "I - M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max,", "= None self.matrix = None self.inv = None self.l = None self.u =", ":return: Nothing. \"\"\" for mtype in mtypes: for dim in dims: for dtype", "equation Ax=b for x and the matrix A. :param b: The vector b", ":return: The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf)", "if row == col: arr[row].append(2) elif row - 1 == col or col", "The mtype-values to use. :param dims: The dimensions to use. :param dtypes: The", "- 1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr =", "Tuple l,u of matrices \"\"\" if self.l is None or self.u is None:", "self.u def solve(self, b): \"\"\" Solves the equation Ax=b for x and the", "use. :param dims: The dimensions to use. :param dtypes: The dtype-values to use.", "matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described", "\"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n,", "described. See start.py for more information. :return: Nothing. \"\"\" if experiment == \"3.1B\":", "mtype-values to use. :param dims: The dimensions to use. :param dtypes: The dtype-values", "dimensions to use. :param dtypes: The dtype-values to use. :return: Nothing. \"\"\" for", "'saite'.\") self.mtype = mtype if dim <= 0: raise Exception(\"dim must be >", "constructor and its inverse. :return: Nothing. \"\"\" arr = [] if self.mtype ==", "self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values given to the", "+ 1): result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result)", "operations with an hilbert- or a special triangular matrix. \"\"\" def __init__(self, mtype,", "None self.inv = None self.l = None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self):", "i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i))", "n, dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n,", "main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments", "def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described in 3.1B. :param mtypes:", "== col or col - 1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype", "M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\"", "dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See start.py for more", "in 3.2B :param dtypes: the data-type to use (float16, float32 or float64) :param", "experiments as described. See start.py for more information. :return: Nothing. \"\"\" if experiment", "the values given to the constructor and its inverse. :return: Nothing. \"\"\" arr", "dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype)", "i_max in i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment,", "self.l is None or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return", "0\") self.dim = dim if dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown", "use (float16, float32 or float64) :param n_iterable: The n-values to use. :param i_iterable:", ":param n_iterable: The n-values to use. :param i_iterable: The i-values to use. (if", ":param b: The vector b to solve the Matrix for. :return: The vector", "as described in 3.1B. :param mtypes: The mtype-values to use. :param dims: The", "\"\"\" Provides Methods for operations with an hilbert- or a special triangular matrix.", "(\"hilbert\" or \"saite\" for triangular) :param dim: The dimension. Must be > 0.", "self.dim = dim if dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype.", "Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m)", "except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of M: \" + ex.message)", "solve(self, b): \"\"\" Solves the equation Ax=b for x and the matrix A.", "Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor =", "create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values given to the constructor and", "dimension to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix", "= numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable,", "(float16, float32 or float64) :param n_iterable: The n-values to use. :param i_iterable: The", "The matrix type (\"hilbert\" or \"saite\" for triangular) :param dim: The dimension. Must", "'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix = None self.inv = None", "A\": for n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes,", "raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype if dim", "Executes experiments as described in 3.1B. :param mtypes: The mtype-values to use. :param", "use. :param dtypes: The dtype-values to use. :return: Nothing. \"\"\" for mtype in", "dtype) matrix = Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try:", "self.matrix = None self.inv = None self.l = None self.u = None self.create_matrix_and_inv()", ":param dims: The dimensions to use. :param dtypes: The dtype-values to use. :return:", "vector b to solve the Matrix for. :return: The vector x from Ax=b.", "use :param dtype: the data-type to use (float16, float32 or float64) :param n:", "xrange(0, self.dim): if row == col: arr[row].append(2) elif row - 1 == col", "dtype, n): \"\"\" Executes experiments as described in 3.2B B. (Hilbert) :param i_max:", "None or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u", "if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and", "Initializes the class instance. :param mtype: The matrix type (\"hilbert\" or \"saite\" for", "\"saite\" for triangular) :param dim: The dimension. Must be > 0. :param dtype:", "self.l, self.u def solve(self, b): \"\"\" Solves the equation Ax=b for x and", "mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See start.py for", "ignored). :return: Nothing. \"\"\" for dtype in dtypes: for n in n_iterable: for", "to the constructor and its inverse. :return: Nothing. \"\"\" arr = [] if", "= Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv =", "mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype if dim <= 0:", "Allowed are 'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix", "arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv", "3.2B B. (Hilbert) :param i_max: The maximum i to use :param dtype: the", "<NAME> (lambertt) and <NAME> (odafaluy) import numpy import scipy import scipy.linalg import plot", "def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See", "main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described in 3.2B", "b): \"\"\" Solves the equation Ax=b for x and the matrix A. :param", "= dtype self.dtype_constructor = None self.matrix = None self.inv = None self.l =", "use. :return: Nothing. \"\"\" for mtype in mtypes: for dim in dims: for", "The vector b to solve the Matrix for. :return: The vector x from", "print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for", "the matrix into l (left lower) and u (right upper) matrices. (Matrix A", "for i in xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i =", ":return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment ==", "b to solve the Matrix for. :return: The vector x from Ax=b. \"\"\"", "x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described", "row == col: arr[row].append(2) elif row - 1 == col or col -", "to use :param dtype: the data-type to use (float16, float32 or float64) :param", "def __init__(self, mtype, dim, dtype): \"\"\" Initializes the class instance. :param mtype: The", "Ax=b for x and the matrix A. :param b: The vector b to", "(odafaluy) import numpy import scipy import scipy.linalg import plot class Matrix: \"\"\" Provides", "* numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into l (left lower)", "dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype)", "and u (right upper) matrices. (Matrix A = LU) :return: A Tuple l,u", "values given to the constructor and its inverse. :return: Nothing. \"\"\" arr =", "elif row - 1 == col or col - 1 == row: arr[row].append(-1)", "main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described in 3.1B. :param mtypes: The", "(left lower) and u (right upper) matrices. (Matrix A = LU) :return: A", "x from Ax=b. \"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True)", "for dtype in dtypes: for n in n_iterable: for i_max in i_iterable: if", "solve the Matrix for. :return: The vector x from Ax=b. \"\"\" l, u", "n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes, n_iterable, i_iterable) else: print(\"Unknown", "be ignored). :return: Nothing. \"\"\" for dtype in dtypes: for n in n_iterable:", "None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b): \"\"\"", "Calculates the condition of the matrix. :return: The condition of the matrix. \"\"\"", "for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity", "None self.l = None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the", "dtype in dtypes: for n in n_iterable: for i_max in i_iterable: if i_max", "scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the", "type to use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not", "n_iterable: for i_max in i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype, n)", "experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B - A\": for", "def condition(self): \"\"\" Calculates the condition of the matrix. :return: The condition of", "> 0\") self.dim = dim if dtype not in [\"float16\", \"float32\", \"float64\"]: raise", "\"\"\" Calculates the matrix from the values given to the constructor and its", "n_iterable, i_iterable): \"\"\" Executes experiments as described in 3.2B :param dtypes: the data-type", "of the matrix. :return: The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf)", ":param i_max: The maximum i to use :param dtype: the data-type to use", "Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype if dim <=", "(lambertt) and <NAME> (odafaluy) import numpy import scipy import scipy.linalg import plot class", "as described. See start.py for more information. :return: Nothing. \"\"\" if experiment ==", "numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into l (left lower) and", "import scipy.linalg import plot class Matrix: \"\"\" Provides Methods for operations with an", ":param dtype: The type to use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\"", "i in xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i = {0},", "or a special triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes", "matrix from the values given to the constructor and its inverse. :return: Nothing.", "[\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype", "or float64) :param n_iterable: The n-values to use. :param i_iterable: The i-values to", "for triangular) :param dim: The dimension. Must be > 0. :param dtype: The", "scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of M: \" +", "and <NAME> (odafaluy) import numpy import scipy import scipy.linalg import plot class Matrix:", "= self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return", "the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits", "dims, dtypes): \"\"\" Executes experiments as described in 3.1B. :param mtypes: The mtype-values", "self.mtype == \"saite\": for row in xrange(0, self.dim): arr.append([]) for col in xrange(0,", "numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I - M M^(-1) || = {0}\".format(condition,", "n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes, n_iterable, i_iterable)", ":param mtypes: The mtype-values to use. :param dims: The dimensions to use. :param", "numpy import scipy import scipy.linalg import plot class Matrix: \"\"\" Provides Methods for", "mtype if dim <= 0: raise Exception(\"dim must be > 0\") self.dim =", "main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See start.py", "1 == col or col - 1 == row: arr[row].append(-1) else: arr[row].append(0) if", "more information. :return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif", "def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described in 3.2B B. (Hilbert)", "or \"saite\" for triangular) :param dim: The dimension. Must be > 0. :param", "0: raise Exception(\"dim must be > 0\") self.dim = dim if dtype not", "numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I - M M^(-1)", "\"\"\" Calculates the condition of the matrix. :return: The condition of the matrix.", "start.py for more information. :return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims,", "matrix into l (left lower) and u (right upper) matrices. (Matrix A =", "= mtype if dim <= 0: raise Exception(\"dim must be > 0\") self.dim", "col or col - 1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype ==", "Exception(\"dim must be > 0\") self.dim = dim if dtype not in [\"float16\",", "matrices. (Matrix A = LU) :return: A Tuple l,u of matrices \"\"\" if", "= None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from", "the data-type to use (float16, float32 or float64) :param n: The dimension to", "maximum i to use :param dtype: the data-type to use (float16, float32 or", "else: arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype)", "<= 0: raise Exception(\"dim must be > 0\") self.dim = dim if dtype", "the matrix from the values given to the constructor and its inverse. :return:", "use. :param i_iterable: The i-values to use. (if i>n it will be ignored).", "float32 or float64) :param n: The dimension to use. :return: Nothing. \"\"\" matrix", "try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of", "main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described in 3.2B :param dtypes: the", "= dim if dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed", "n): \"\"\" Executes experiments as described in 3.2B B. (Hilbert) :param i_max: The", "n-values to use. :param i_iterable: The i-values to use. (if i>n it will", "- M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype,", "\"\"\" arr = [] if self.mtype == \"saite\": for row in xrange(0, self.dim):", "an hilbert- or a special triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype):", "described in 3.2B :param dtypes: the data-type to use (float16, float32 or float64)", "in xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0}", "result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes,", "== \"saite\": for row in xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim):", "self.dim): if row == col: arr[row].append(2) elif row - 1 == col or", "x and the matrix A. :param b: The vector b to solve the", "n in n_iterable: for i_max in i_iterable: if i_max > n: continue main_32b_hilbert(i_max,", "i_iterable=None): \"\"\" Executes experiments as described. See start.py for more information. :return: Nothing.", "dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity =", "identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex:", "lu(self): \"\"\" Splits the matrix into l (left lower) and u (right upper)", "experiments as described in 3.1B. :param mtypes: The mtype-values to use. :param dims:", "Provides Methods for operations with an hilbert- or a special triangular matrix. \"\"\"", "The dtype-values to use. :return: Nothing. \"\"\" for mtype in mtypes: for dim", "Ax=b. \"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x =", "ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into l (left lower) and u", "continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes", "for. :return: The vector x from Ax=b. \"\"\" l, u = self.lu() x", "condition of the matrix. :return: The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix,", "dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m", "arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr,", "with an hilbert- or a special triangular matrix. \"\"\" def __init__(self, mtype, dim,", "information. :return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment", "== \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B - A\": for n", "for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype,", "dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError,", "dtype: the data-type to use (float16, float32 or float64) :param n: The dimension", "self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition", "permute_l=True) return self.l, self.u def solve(self, b): \"\"\" Solves the equation Ax=b for", "Executes experiments as described. See start.py for more information. :return: Nothing. \"\"\" if", "triangular) :param dim: The dimension. Must be > 0. :param dtype: The type", "b: The vector b to solve the Matrix for. :return: The vector x", ":param dtypes: The dtype-values to use. :return: Nothing. \"\"\" for mtype in mtypes:", "i>n it will be ignored). :return: Nothing. \"\"\" for dtype in dtypes: for", "self.l = None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix", "not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and", ":param i_iterable: The i-values to use. (if i>n it will be ignored). :return:", "import plot class Matrix: \"\"\" Provides Methods for operations with an hilbert- or", "if dim <= 0: raise Exception(\"dim must be > 0\") self.dim = dim", "self.dtype = dtype self.dtype_constructor = None self.matrix = None self.inv = None self.l", "data-type to use (float16, float32 or float64) :param n_iterable: The n-values to use.", "self.dtype_constructor = None self.matrix = None self.inv = None self.l = None self.u", "M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n):", "continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I", "import scipy import scipy.linalg import plot class Matrix: \"\"\" Provides Methods for operations", "dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except", "use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0}", "and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i in xrange(1, i_max", "= {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments", "[] if self.mtype == \"saite\": for row in xrange(0, self.dim): arr.append([]) for col", "experiments as described in 3.2B :param dtypes: the data-type to use (float16, float32", "ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I - M M^(-1) ||", "> n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None):", "<NAME> (odafaluy) import numpy import scipy import scipy.linalg import plot class Matrix: \"\"\"", "dtypes: for n in n_iterable: for i_max in i_iterable: if i_max > n:", "n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See start.py for more information. :return:", "matrix. :return: The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv,", "= None self.inv = None self.l = None self.u = None self.create_matrix_and_inv() def", "use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not in [\"saite\",", "mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim,", "described in 3.1B. :param mtypes: The mtype-values to use. :param dims: The dimensions", "l, u = self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x,", "not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype", "\"\"\" for dtype in dtypes: for n in n_iterable: for i_max in i_iterable:", "\"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype if", "{0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as", "3.2B :param dtypes: the data-type to use (float16, float32 or float64) :param n_iterable:", "in xrange(0, self.dim): if row == col: arr[row].append(2) elif row - 1 ==", "is None or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l,", "Authors: <NAME> (lambertt) and <NAME> (odafaluy) import numpy import scipy import scipy.linalg import", "xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i = {0}, x^{0} =", "import numpy import scipy import scipy.linalg import plot class Matrix: \"\"\" Provides Methods", "The condition of the matrix. \"\"\" return numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def", "Matrix with n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i", "if i_max > n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None,", "to use (float16, float32 or float64) :param n_iterable: The n-values to use. :param", "to use. :param i_iterable: The i-values to use. (if i>n it will be", "\"\"\" Executes experiments as described in 3.2B :param dtypes: the data-type to use", "The dimension to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert", "self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self,", "Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]:", "a special triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes the", "type (\"hilbert\" or \"saite\" for triangular) :param dim: The dimension. Must be >", "the Matrix for. :return: The vector x from Ax=b. \"\"\" l, u =", "Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B", "main_32b_hilbert(i_max, dtype, n): \"\"\" Executes experiments as described in 3.2B B. (Hilbert) :param", "dtypes: The dtype-values to use. :return: Nothing. \"\"\" for mtype in mtypes: for", "def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described in 3.2B :param dtypes:", "A = LU) :return: A Tuple l,u of matrices \"\"\" if self.l is", "The dimension. Must be > 0. :param dtype: The type to use. Can", "as described in 3.2B B. (Hilbert) :param i_max: The maximum i to use", "== row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix", "- A\": for n in n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\":", "(numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of M: \" + ex.message) continue", "print(\"Cannot calculate inverse of M: \" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf)", "arr[row].append(2) elif row - 1 == col or col - 1 == row:", "in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim,", "ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into l (left", "dtype self.dtype_constructor = None self.matrix = None self.inv = None self.l = None", "== \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def", "scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of the matrix. :return: The condition", "dtypes) elif experiment == \"3.2B - A\": for n in n_iterable: main_32b_saite(n) elif", "xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim): if row == col: arr[row].append(2)", "self.dim): arr.append([]) for col in xrange(0, self.dim): if row == col: arr[row].append(2) elif", "|| I - M M^(-1) || = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def", ":return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and", "lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\"", "dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m = identity", "result = numpy.identity(n, dtype=dtype) for i in xrange(1, i_max + 1): result =", "mtype in mtypes: for dim in dims: for dtype in dtypes: print(\"\") print(\"Experiment", "to use. (if i>n it will be ignored). :return: Nothing. \"\"\" for dtype", "[\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype", "row in xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim): if row ==", "use (float16, float32 or float64) :param n: The dimension to use. :return: Nothing.", "lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as described in", "print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix", "self.lu() x = scipy.linalg.solve_triangular(l, b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x", "experiments as described in 3.2B B. (Hilbert) :param i_max: The maximum i to", "or float64) :param n: The dimension to use. :return: Nothing. \"\"\" matrix =", "in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown mtype. Allowed are 'hilbert' and 'saite'.\") self.mtype =", "identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m = identity -", "class instance. :param mtype: The matrix type (\"hilbert\" or \"saite\" for triangular) :param", "dtype: The type to use. Can be \"float16\", \"float32\" or \"flaot64\" \"\"\" if", "dims: for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype))", "arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\"", "dtype=dtype) for i in xrange(1, i_max + 1): result = numpy.dot(result, matrix.matrix) print(\"i", ":return: Nothing. \"\"\" for dtype in dtypes: for n in n_iterable: for i_max", "= numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix,", "= \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described in", "for i_max in i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype, n) def", "= [] if self.mtype == \"saite\": for row in xrange(0, self.dim): arr.append([]) for", "Allowed are 'hilbert' and 'saite'.\") self.mtype = mtype if dim <= 0: raise", "i_max > n: continue main_32b_hilbert(i_max, dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None,", "u (right upper) matrices. (Matrix A = LU) :return: A Tuple l,u of", "LU) :return: A Tuple l,u of matrices \"\"\" if self.l is None or", "float32 or float64) :param n_iterable: The n-values to use. :param i_iterable: The i-values", "dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype)", "def lu(self): \"\"\" Splits the matrix into l (left lower) and u (right", "mtype, dim, dtype): \"\"\" Initializes the class instance. :param mtype: The matrix type", "are 'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix =", "self.mtype = mtype if dim <= 0: raise Exception(\"dim must be > 0\")", "Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype)) result =", "self.inv = None self.l = None self.u = None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\"", "for more information. :return: Nothing. \"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes)", "= {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments", "dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as described. See start.py for more information.", "col in xrange(0, self.dim): if row == col: arr[row].append(2) elif row - 1", "of M: \" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf)", "the matrix A. :param b: The vector b to solve the Matrix for.", "The dimensions to use. :param dtypes: The dtype-values to use. :return: Nothing. \"\"\"", "= numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I - M", "float64) :param n_iterable: The n-values to use. :param i_iterable: The i-values to use.", "\"\"\" Executes experiments as described in 3.1B. :param mtypes: The mtype-values to use.", "None self.create_matrix_and_inv() def create_matrix_and_inv(self): \"\"\" Calculates the matrix from the values given to", "= identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as", "dimension. Must be > 0. :param dtype: The type to use. Can be", "n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i in xrange(1,", "numpy.linalg.norm(self.matrix, ord=numpy.inf) * numpy.linalg.norm(self.inv, ord=numpy.inf) def lu(self): \"\"\" Splits the matrix into l", ":return: Nothing. \"\"\" arr = [] if self.mtype == \"saite\": for row in", "matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes the class instance. :param", "special triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\" Initializes the class", "dims, dtypes) elif experiment == \"3.2B - A\": for n in n_iterable: main_32b_saite(n)", "{1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i in xrange(1, i_max + 1):", "to use. :param dims: The dimensions to use. :param dtypes: The dtype-values to", "for x and the matrix A. :param b: The vector b to solve", "\"\"\" for mtype in mtypes: for dim in dims: for dtype in dtypes:", "for col in xrange(0, self.dim): if row == col: arr[row].append(2) elif row -", "or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def", ":param n: The dimension to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n,", "dtypes: the data-type to use (float16, float32 or float64) :param n_iterable: The n-values", "ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} ||", "matrix type (\"hilbert\" or \"saite\" for triangular) :param dim: The dimension. Must be", "float64) :param n: The dimension to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\",", "\"\"\" if self.l is None or self.u is None: self.l, self.u = scipy.linalg.lu(self.matrix,", "None self.matrix = None self.inv = None self.l = None self.u = None", "__init__(self, mtype, dim, dtype): \"\"\" Initializes the class instance. :param mtype: The matrix", "(Hilbert) :param i_max: The maximum i to use :param dtype: the data-type to", "\".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes experiments as described in 3.2B", "scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments as", "(right upper) matrices. (Matrix A = LU) :return: A Tuple l,u of matrices", "self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b): \"\"\" Solves the", "raise Exception(\"dim must be > 0\") self.dim = dim if dtype not in", "Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and type", "arr = [] if self.mtype == \"saite\": for row in xrange(0, self.dim): arr.append([])", "dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of the matrix.", "matrix A. :param b: The vector b to solve the Matrix for. :return:", "\"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self):", "dim: The dimension. Must be > 0. :param dtype: The type to use.", "\"float16\", \"float32\" or \"flaot64\" \"\"\" if mtype not in [\"saite\", \"hilbert\"]: raise Exception(\"Unknown", "dtypes): \"\"\" Executes experiments as described in 3.1B. :param mtypes: The mtype-values to", "if dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16',", "calculate inverse of M: \" + ex.message) continue condition = numpy.linalg.norm(m, ord=numpy.inf) *", "ValueError) as ex: print(\"Cannot calculate inverse of M: \" + ex.message) continue condition", "be > 0\") self.dim = dim if dtype not in [\"float16\", \"float32\", \"float64\"]:", "scipy import scipy.linalg import plot class Matrix: \"\"\" Provides Methods for operations with", "m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of M:", "\"\"\" if experiment == \"3.1B\": main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B -", "= Matrix(\"hilbert\", n, dtype) print(\"Hilbert Matrix with n={0} and type {1}\".format(n, dtype)) result", "vector x from Ax=b. \"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l, b,", "to solve the Matrix for. :return: The vector x from Ax=b. \"\"\" l,", "- 1 == col or col - 1 == row: arr[row].append(-1) else: arr[row].append(0)", "The maximum i to use :param dtype: the data-type to use (float16, float32", "hilbert- or a special triangular matrix. \"\"\" def __init__(self, mtype, dim, dtype): \"\"\"", "matrix.inv)) try: m_inv = scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse", "|| = {0}\".format(condition, matrix.condition())) def main_32b_saite(n): plot.plot(n) def main_32b_hilbert(i_max, dtype, n): \"\"\" Executes", "main_31b(mtypes, dims, dtypes) elif experiment == \"3.2B - A\": for n in n_iterable:", "condition(self): \"\"\" Calculates the condition of the matrix. :return: The condition of the", "= numpy.identity(n, dtype=dtype) for i in xrange(1, i_max + 1): result = numpy.dot(result,", "and 'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix = None self.inv =", "(if i>n it will be ignored). :return: Nothing. \"\"\" for dtype in dtypes:", "dtype, n) def main(experiment, mtypes=None, dims=None, dtypes=None, n_iterable=None, i_iterable=None): \"\"\" Executes experiments as", "Solves the equation Ax=b for x and the matrix A. :param b: The", "matrix = Matrix(mtype, dim, dtype) m = identity - (numpy.dot(matrix.matrix, matrix.inv)) try: m_inv", "for operations with an hilbert- or a special triangular matrix. \"\"\" def __init__(self,", "mtype: The matrix type (\"hilbert\" or \"saite\" for triangular) :param dim: The dimension.", "= scipy.linalg.inv(m) except (numpy.linalg.linalg.LinAlgError, ValueError) as ex: print(\"Cannot calculate inverse of M: \"", "print(\"i = {0}, x^{0} = \".format(i)) print(result) def main_32b(dtypes, n_iterable, i_iterable): \"\"\" Executes", "with n={0} and type {1}\".format(n, dtype)) result = numpy.identity(n, dtype=dtype) for i in", "'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix = None self.inv", "upper) matrices. (Matrix A = LU) :return: A Tuple l,u of matrices \"\"\"", "b, lower=True) x = scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims, dtypes):", "raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor", "Must be > 0. :param dtype: The type to use. Can be \"float16\",", "Nothing. \"\"\" arr = [] if self.mtype == \"saite\": for row in xrange(0,", "and 'saite'.\") self.mtype = mtype if dim <= 0: raise Exception(\"dim must be", "scipy.linalg import plot class Matrix: \"\"\" Provides Methods for operations with an hilbert-", "\"\"\" Splits the matrix into l (left lower) and u (right upper) matrices.", "= numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of", "print(\"Experiment for mtype={0}, dim={1}, dtype={2}\".format(mtype, dim, dtype)) identity = numpy.identity(dim, dtype) matrix =", "as ex: print(\"Cannot calculate inverse of M: \" + ex.message) continue condition =", "= scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b): \"\"\" Solves the equation", "described in 3.2B B. (Hilbert) :param i_max: The maximum i to use :param", "l (left lower) and u (right upper) matrices. (Matrix A = LU) :return:", "self.inv = scipy.linalg.inv(self.matrix) def condition(self): \"\"\" Calculates the condition of the matrix. :return:", "condition = numpy.linalg.norm(m, ord=numpy.inf) * numpy.linalg.norm(m_inv, ord=numpy.inf) print(\"cond(M) = {1} || I -", "from the values given to the constructor and its inverse. :return: Nothing. \"\"\"", "or col - 1 == row: arr[row].append(-1) else: arr[row].append(0) if self.mtype == \"hilbert\":", "= scipy.linalg.solve_triangular(u, x, lower=False) return x def main_31b(mtypes, dims, dtypes): \"\"\" Executes experiments", "in n_iterable: for i_max in i_iterable: if i_max > n: continue main_32b_hilbert(i_max, dtype,", "in mtypes: for dim in dims: for dtype in dtypes: print(\"\") print(\"Experiment for", "dtype not in [\"float16\", \"float32\", \"float64\"]: raise Exception(\"Unknown dtype. Allowed are 'float16', 'float32'", "arr.append([]) for col in xrange(0, self.dim): if row == col: arr[row].append(2) elif row", "Splits the matrix into l (left lower) and u (right upper) matrices. (Matrix", "in n_iterable: main_32b_saite(n) elif experiment == \"3.2B - B\": main_32b(dtypes, n_iterable, i_iterable) else:", "col: arr[row].append(2) elif row - 1 == col or col - 1 ==", "Executes experiments as described in 3.2B :param dtypes: the data-type to use (float16,", "Nothing. \"\"\" for mtype in mtypes: for dim in dims: for dtype in", "'float16', 'float32' and 'float64'.\") self.dtype = dtype self.dtype_constructor = None self.matrix = None", "mtypes: for dim in dims: for dtype in dtypes: print(\"\") print(\"Experiment for mtype={0},", "i_iterable: The i-values to use. (if i>n it will be ignored). :return: Nothing.", "The vector x from Ax=b. \"\"\" l, u = self.lu() x = scipy.linalg.solve_triangular(l,", "be > 0. :param dtype: The type to use. Can be \"float16\", \"float32\"", "Matrix: \"\"\" Provides Methods for operations with an hilbert- or a special triangular", "if self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv =", "n: The dimension to use. :return: Nothing. \"\"\" matrix = Matrix(\"hilbert\", n, dtype)", "is None: self.l, self.u = scipy.linalg.lu(self.matrix, permute_l=True) return self.l, self.u def solve(self, b):", ":param dtype: the data-type to use (float16, float32 or float64) :param n: The", "dim, dtype)) identity = numpy.identity(dim, dtype) matrix = Matrix(mtype, dim, dtype) m =", "in xrange(0, self.dim): arr.append([]) for col in xrange(0, self.dim): if row == col:", "def solve(self, b): \"\"\" Solves the equation Ax=b for x and the matrix", "will be ignored). :return: Nothing. \"\"\" for dtype in dtypes: for n in", "the condition of the matrix. :return: The condition of the matrix. \"\"\" return", "Executes experiments as described in 3.2B B. (Hilbert) :param i_max: The maximum i", "self.mtype == \"hilbert\": arr = scipy.linalg.hilbert(self.dim).tolist() self.matrix = numpy.array(arr, dtype=self.dtype) self.inv = scipy.linalg.inv(self.matrix)", "inverse. :return: Nothing. \"\"\" arr = [] if self.mtype == \"saite\": for row" ]
[ "self.left = left self.top = top self.width = width self.height = height def", "return self.top if index == 2: return self.width if index == 3: return", "if event.button is 1: p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0],", "quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree)", "from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree =", "toast.scene_graph import GameObject, Scene from toast.camera import Camera from toast.event_manager import EventManager from", "is not []: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left,", "item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent,", "if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface,", "from toast.camera import Camera from toast.event_manager import EventManager from examples.demo_game import DemoGame class", "Scene from toast.camera import Camera from toast.event_manager import EventManager from examples.demo_game import DemoGame", "if index == 2: return self.width if index == 3: return self.height def", "width self.height = height def __getitem__(self, index): if index == 0: return self.left", "index): if index == 0: return self.left if index == 1: return self.top", "self.top if index == 2: return self.width if index == 3: return self.height", "Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256 w = h = 2**9", "index == 0: return self.left if index == 1: return self.top if index", "self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is", "= width self.height = height def __getitem__(self, index): if index == 0: return", "3: return self.height def render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height", "if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface,", "import GameObject, Scene from toast.camera import Camera from toast.event_manager import EventManager from examples.demo_game", "not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree", "from toast.event_manager import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree):", "quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree)", "1: p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d))", "0: return self.left if index == 1: return self.top if index == 2:", "is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if", "GameObject, Scene from toast.camera import Camera from toast.event_manager import EventManager from examples.demo_game import", "(255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is", "DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game = DemoGame((512,", "256 w = h = 2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region)", "render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface,", "QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1: p = DemoGame.camera_to_world(event.pos)", "quadtree.bucket is not []: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self,", "self.top = top self.width = width self.height = height def __getitem__(self, index): if", "render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1)", "def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant,", "NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position =", "__init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree)", "examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree", "if index == 0: return self.left if index == 1: return self.top if", "== 3: return self.height def render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width,", "class RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left = left", "region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button", "super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self,", "render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1)", "QuadTree from toast.scene_graph import GameObject, Scene from toast.camera import Camera from toast.event_manager import", "self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1: p", "import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__()", "= left self.top = top self.width = width self.height = height def __getitem__(self,", "None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is", "__getitem__(self, index): if index == 0: return self.left if index == 1: return", "from toast.scene_graph import GameObject, Scene from toast.camera import Camera from toast.event_manager import EventManager", "is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for item in", "self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self,", "is 1: p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d,", "256, 256 w = h = 2**9 region = (0,0,w,h) self.quadtree = QuadTree([],", "EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree", "import pygame import random from toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene", "index == 3: return self.height def render(self, surface, offset=(0,0)): rect = self.left, self.top,", "pygame import random from toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene from", "not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree", "self).__init__() self.left = left self.top = top self.width = width self.height = height", "'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256 w = h =", "Camera from toast.event_manager import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self,", "= QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1: p =", "= 512, 512 Camera.current_camera.position = 256, 256 w = h = 2**9 region", "def onMouseDown(self, event): if event.button is 1: p = DemoGame.camera_to_world(event.pos) d = 2", "self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface,", "if index == 3: return self.height def render(self, surface, offset=(0,0)): rect = self.left,", "self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown')", "h = 2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self,", "(255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport =", "= top self.width = width self.height = height def __getitem__(self, index): if index", "== 2: return self.width if index == 3: return self.height def render(self, surface,", "512 Camera.current_camera.position = 256, 256 w = h = 2**9 region = (0,0,w,h)", "self.width if index == 3: return self.height def render(self, surface, offset=(0,0)): rect =", "return self.left if index == 1: return self.top if index == 2: return", "offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene):", "self.left if index == 1: return self.top if index == 2: return self.width", "RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left = left self.top", "offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree", "import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def", "toast.event_manager import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer,", "None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is", "from toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene from toast.camera import Camera", "if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for", "= 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game = DemoGame((512, 512), NewScene)", "import QuadTree from toast.scene_graph import GameObject, Scene from toast.camera import Camera from toast.event_manager", "toast.camera import Camera from toast.event_manager import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject):", "quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for item", "= 2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event):", "quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0),", "not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket", "== 0: return self.left if index == 1: return self.top if index ==", "self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene,", "not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for item in quadtree.bucket:", "1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512", "def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256,", "2: return self.width if index == 3: return self.height def render(self, surface, offset=(0,0)):", "quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not", "self.height = height def __getitem__(self, index): if index == 0: return self.left if", "= (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is", "EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256 w = h", "not []: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top,", "self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not", "index == 1: return self.top if index == 2: return self.width if index", "2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if", "self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not", "class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface,", "height def __getitem__(self, index): if index == 0: return self.left if index ==", "top self.width = width self.height = height def __getitem__(self, index): if index ==", "quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None:", "class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position", "def __getitem__(self, index): if index == 0: return self.left if index == 1:", "pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree", "pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport", "= self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self):", "super(RectComponent, self).__init__() self.left = left self.top = top self.width = width self.height =", "def __init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left = left self.top =", "self.height def render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255),", "region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1: p = DemoGame.camera_to_world(event.pos) d", "(0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1:", "__init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256", "d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game = DemoGame((512, 512),", "surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class", "quadtree.southeast_tree) if quadtree.bucket is not []: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject):", "rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def", "quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if", "if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface,", "self.add(QuadTreeVisualizer(self.quadtree)) def onMouseDown(self, event): if event.button is 1: p = DemoGame.camera_to_world(event.pos) d =", "toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene from toast.camera import Camera from", "if index == 1: return self.top if index == 2: return self.width if", "def render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect,", "QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)):", "quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree)", "onMouseDown(self, event): if event.button is 1: p = DemoGame.camera_to_world(event.pos) d = 2 **", "item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left =", "None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is", "self.top, self.width, self.height pygame.draw.rect(surface, (255,255,255), rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__()", "surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree)", "1: return self.top if index == 2: return self.width if index == 3:", "DemoGame class QuadTreeVisualizer(GameObject): def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self,", "def __init__(self, quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface,", "index == 2: return self.width if index == 3: return self.height def render(self,", "self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not", "[]: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width,", "= 256, 256 w = h = 2**9 region = (0,0,w,h) self.quadtree =", "event): if event.button is 1: p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5)", "quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left", "Camera.current_camera.position = 256, 256 w = h = 2**9 region = (0,0,w,h) self.quadtree", "is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None: self.render_quadtree(surface, quadtree.southwest_tree) if", "self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not", "= h = 2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree)) def", "random from toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene from toast.camera import", "self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256 w =", "self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree):", "__init__(self, left, top, width, height): super(RectComponent, self).__init__() self.left = left self.top = top", "import random from toast.quadtree import QuadTree from toast.scene_graph import GameObject, Scene from toast.camera", "quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []:", "super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512, 512 Camera.current_camera.position = 256, 256 w", "None: self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for item in quadtree.bucket: item.render(surface)", "width, height): super(RectComponent, self).__init__() self.left = left self.top = top self.width = width", "import Camera from toast.event_manager import EventManager from examples.demo_game import DemoGame class QuadTreeVisualizer(GameObject): def", "return self.height def render(self, surface, offset=(0,0)): rect = self.left, self.top, self.width, self.height pygame.draw.rect(surface,", "if quadtree.bucket is not []: for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def", "rect, 1) class NewScene(Scene): def __init__(self): super(NewScene, self).__init__() EventManager.subscribe(self, 'onMouseDown') Camera.current_camera.viewport = 512,", "self.width = width self.height = height def __getitem__(self, index): if index == 0:", "left, top, width, height): super(RectComponent, self).__init__() self.left = left self.top = top self.width", "quadtree): super(QuadTreeVisualizer, self).__init__() self.quadtree = quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def", "is not None: self.render_quadtree(surface, quadtree.southwest_tree) if quadtree.southeast_tree is not None: self.render_quadtree(surface, quadtree.southeast_tree) if", "left self.top = top self.width = width self.height = height def __getitem__(self, index):", "return self.width if index == 3: return self.height def render(self, surface, offset=(0,0)): rect", "def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if quadtree.northwest_tree is not None:", "in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width, height): super(RectComponent, self).__init__()", "1) if quadtree.northwest_tree is not None: self.render_quadtree(surface, quadtree.northwest_tree) if quadtree.northeast_tree is not None:", "height): super(RectComponent, self).__init__() self.left = left self.top = top self.width = width self.height", "top, width, height): super(RectComponent, self).__init__() self.left = left self.top = top self.width =", "event.button is 1: p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1],", "== 1: return self.top if index == 2: return self.width if index ==", "self.render_quadtree(surface, quadtree.southeast_tree) if quadtree.bucket is not []: for item in quadtree.bucket: item.render(surface) class", "512, 512 Camera.current_camera.position = 256, 256 w = h = 2**9 region =", "w = h = 2**9 region = (0,0,w,h) self.quadtree = QuadTree([], region) self.add(QuadTreeVisualizer(self.quadtree))", "2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game = DemoGame((512, 512), NewScene) game.run()", "p = DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game", "= DemoGame.camera_to_world(event.pos) d = 2 ** random.randint(1,5) self.quadtree.insert(RectComponent(p[0], p[1], d, d)) game =", "surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface, (255,0,0), quadtree.quadrant, 1) if", "quadtree.northwest_tree) if quadtree.northeast_tree is not None: self.render_quadtree(surface, quadtree.northeast_tree) if quadtree.southwest_tree is not None:", "for item in quadtree.bucket: item.render(surface) class RectComponent(GameObject): def __init__(self, left, top, width, height):", "= height def __getitem__(self, index): if index == 0: return self.left if index", "= quadtree def render(self, surface, offset=(0,0)): self.render_quadtree(surface, self.quadtree) def render_quadtree(self, surface, quadtree): pygame.draw.rect(surface," ]
[ "downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('tiles',", "c1ca0249cb60 Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op import", "= 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on = None def upgrade():", "down_revision = '0b986a10b559' branch_labels = None depends_on = None def upgrade(): # ###", "auto generated by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles',", "by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(),", "by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on =", "08:36:09.067866 \"\"\" from alembic import op import sqlalchemy as sa # revision identifiers,", "= '0b986a10b559' branch_labels = None depends_on = None def upgrade(): # ### commands", "def upgrade(): # ### commands auto generated by Alembic - please adjust! ###", "None def upgrade(): # ### commands auto generated by Alembic - please adjust!", "Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op import sqlalchemy", "Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op import sqlalchemy as sa #", "'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on = None def upgrade(): #", "op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands ### def downgrade(): #", "# ### commands auto generated by Alembic - please adjust! ### op.drop_column('tiles', 'min_x')", "generated by Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') # ###", "import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision", "Revision ID: c1ca0249cb60 Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import", "Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on = None", "# ### commands auto generated by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y',", "sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ###", "# ### end Alembic commands ### def downgrade(): # ### commands auto generated", "Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True))", "commands ### def downgrade(): # ### commands auto generated by Alembic - please", "\"\"\"empty message Revision ID: c1ca0249cb60 Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from", "### def downgrade(): # ### commands auto generated by Alembic - please adjust!", "- please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') # ### end Alembic commands", "generated by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x',", "None depends_on = None def upgrade(): # ### commands auto generated by Alembic", "nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands ### def downgrade():", "### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic", "alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic.", "Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') # ### end Alembic", "upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('tiles',", "ID: c1ca0249cb60 Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op", "import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c1ca0249cb60'", "= None depends_on = None def upgrade(): # ### commands auto generated by", "op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands", "by Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') # ### end", "sa # revision identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559'", "auto generated by Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') #", "0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op import sqlalchemy as", "identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None", "sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands ###", "from alembic import op import sqlalchemy as sa # revision identifiers, used by", "### commands auto generated by Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles',", "please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ###", "please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y') # ### end Alembic commands ###", "as sa # revision identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision =", "### commands auto generated by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(),", "### end Alembic commands ### def downgrade(): # ### commands auto generated by", "sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end Alembic commands ### def", "sa.Float(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands", "message Revision ID: c1ca0249cb60 Revises: 0b986a10b559 Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic", "Create Date: 2020-01-07 08:36:09.067866 \"\"\" from alembic import op import sqlalchemy as sa", "revision identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels =", "= None def upgrade(): # ### commands auto generated by Alembic - please", "commands auto generated by Alembic - please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True))", "branch_labels = None depends_on = None def upgrade(): # ### commands auto generated", "Alembic commands ### def downgrade(): # ### commands auto generated by Alembic -", "\"\"\" from alembic import op import sqlalchemy as sa # revision identifiers, used", "op import sqlalchemy as sa # revision identifiers, used by Alembic. revision =", "'0b986a10b559' branch_labels = None depends_on = None def upgrade(): # ### commands auto", "sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision", "- please adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) #", "adjust! ### op.add_column('tiles', sa.Column('max_y', sa.Float(), nullable=True)) op.add_column('tiles', sa.Column('min_x', sa.Float(), nullable=True)) # ### end", "def downgrade(): # ### commands auto generated by Alembic - please adjust! ###", "# revision identifiers, used by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels", "used by Alembic. revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on", "revision = 'c1ca0249cb60' down_revision = '0b986a10b559' branch_labels = None depends_on = None def", "end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic", "2020-01-07 08:36:09.067866 \"\"\" from alembic import op import sqlalchemy as sa # revision", "nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto", "commands auto generated by Alembic - please adjust! ### op.drop_column('tiles', 'min_x') op.drop_column('tiles', 'max_y')", "depends_on = None def upgrade(): # ### commands auto generated by Alembic -" ]
[ "cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def", "self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL,", "from testutils import getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type", "def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression()", "getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression", "= self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE", "self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE", "= self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01", "fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL =", "class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression =", "self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL", "FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE = 0x00 FULL_ADDITIONAL_VALUE", "fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE =", "getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression", "import unittest from testutils import getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api =", "testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL", "10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE = 0x00 FULL_ADDITIONAL_VALUE = 0x03", "fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE = 0x00", "fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL =", "fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value =", "self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE", "import getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self):", "self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE =", "= getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self):", "unittest from testutils import getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__,", "testutils import getZserioApi class FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def", "def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL,", "def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10", "= 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7 FULL_VALID_VALUE = 0x01 FULL_INVALID_VALUE = 0x00 FULL_ADDITIONAL_VALUE =", "= self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof()) FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL = 10 FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL = 7", "\"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression =", "@classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE)", "FullConstTypeTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE,", "self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value = self.FULL_INVALID_VALUE self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITHOUT_OPTIONAL, fullConstTypeExpression.bitsizeof())", "setUpClass(cls): cls.api = getZserioApi(__file__, \"expressions.zs\").full_const_type def testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof())", "testBitSizeOfWithOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression(self.FULL_VALID_VALUE, self.FULL_ADDITIONAL_VALUE) self.assertEqual(self.FULL_CONST_TYPE_EXPRESSION_BIT_SIZE_WITH_OPTIONAL, fullConstTypeExpression.bitsizeof()) def testBitSizeOfWithoutOptional(self): fullConstTypeExpression = self.api.FullConstTypeExpression() fullConstTypeExpression.value" ]
[ "load( gripper_model: Optional[int] = None, gripper_id: Optional[int] = None ) -> GripperConfig: return", "= [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float", "0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model:", "float display_name: str name: GripperName max_travel: float home_position: float steps_per_mm: float idle_current: float", "GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float,", "steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None, gripper_id: Optional[int] =", "model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None, gripper_id: Optional[int] = None )", "= Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig:", "import logging from typing import Tuple, Optional from typing_extensions import Literal log =", "float, float] gripper_current: float display_name: str name: GripperName max_travel: float home_position: float steps_per_mm:", "from typing_extensions import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"]", "import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET =", "name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None,", "display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] =", "= GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\",", "[0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name:", "GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str name: GripperName max_travel: float", "None, gripper_id: Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG # TODO: load", "log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0,", "dataclasses import dataclass import logging from typing import Tuple, Optional from typing_extensions import", "DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current:", "def load( gripper_model: Optional[int] = None, gripper_id: Optional[int] = None ) -> GripperConfig:", "logging from typing import Tuple, Optional from typing_extensions import Literal log = logging.getLogger(__name__)", "gripper_id: Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG # TODO: load actual", "idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\",", "__future__ import annotations from dataclasses import dataclass import logging from typing import Tuple,", "gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def", "float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\",", "Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float]", "typing import Tuple, Optional from typing_extensions import Literal log = logging.getLogger(__name__) GripperName =", "max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None, gripper_id:", "float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0,", "from dataclasses import dataclass import logging from typing import Tuple, Optional from typing_extensions", "max_travel: float home_position: float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig(", "0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str", "home_position: float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0,", "GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0,", "dataclass import logging from typing import Tuple, Optional from typing_extensions import Literal log", "logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True)", "idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None, gripper_id: Optional[int] = None", "from typing import Tuple, Optional from typing_extensions import Literal log = logging.getLogger(__name__) GripperName", "gripper_model: Optional[int] = None, gripper_id: Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG", "gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str name: GripperName max_travel: float home_position:", "from __future__ import annotations from dataclasses import dataclass import logging from typing import", "@dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str name: GripperName", "0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str name:", "steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0,", "display_name: str name: GripperName max_travel: float home_position: float steps_per_mm: float idle_current: float model:", "gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int]", ") def load( gripper_model: Optional[int] = None, gripper_id: Optional[int] = None ) ->", "import annotations from dataclasses import dataclass import logging from typing import Tuple, Optional", "float] gripper_current: float display_name: str name: GripperName max_travel: float home_position: float steps_per_mm: float", "float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0),", "DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2,", "Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0,", "Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset:", "model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0,", "0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load(", "GripperName max_travel: float home_position: float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG =", "= None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG # TODO: load actual gripper config", "import Tuple, Optional from typing_extensions import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"]", "GripperConfig( gripper_offset=(0.0, 0.0, 0.0), gripper_current=1.0, display_name=\"dummy_gripper\", name=\"gripper\", max_travel=50.0, home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", )", "Optional[int] = None, gripper_id: Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG #", "= Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class GripperConfig: gripper_offset: Tuple[float, float,", "Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG # TODO: load actual gripper", "Optional from typing_extensions import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel =", "GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0] @dataclass(frozen=True) class", "import dataclass import logging from typing import Tuple, Optional from typing_extensions import Literal", "float home_position: float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG = GripperConfig( gripper_offset=(0.0,", "class GripperConfig: gripper_offset: Tuple[float, float, float] gripper_current: float display_name: str name: GripperName max_travel:", "typing_extensions import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET", "= None, gripper_id: Optional[int] = None ) -> GripperConfig: return DUMMY_GRIPPER_CONFIG # TODO:", "Tuple[float, float, float] gripper_current: float display_name: str name: GripperName max_travel: float home_position: float", "str name: GripperName max_travel: float home_position: float steps_per_mm: float idle_current: float model: GripperModel", "= logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel = Literal[\"gripper_v1\"] DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0]", "home_position=0.0, steps_per_mm=480.0, idle_current=0.2, model=\"gripper_v1\", ) def load( gripper_model: Optional[int] = None, gripper_id: Optional[int]", "Tuple, Optional from typing_extensions import Literal log = logging.getLogger(__name__) GripperName = Literal[\"gripper\"] GripperModel", "annotations from dataclasses import dataclass import logging from typing import Tuple, Optional from", "name: GripperName max_travel: float home_position: float steps_per_mm: float idle_current: float model: GripperModel DUMMY_GRIPPER_CONFIG", "gripper_current: float display_name: str name: GripperName max_travel: float home_position: float steps_per_mm: float idle_current:" ]
[ "blogs = Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please delete posts and", "categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length =", "Command(BaseCommand): help = \"Deletes categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove categories", "= \"Deletes categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts", "categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if posts or blogs: sys.stdout.write(", "if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to", "from cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes categories (bulk action)\" def", "Post.objects.all() blogs = Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please delete posts", "= Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs", "or blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs before running this commend\\n\"", "<gh_stars>0 import sys from django.core.management.base import BaseCommand from cms.categories.models import Category from cms.posts.models", "blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs before running this commend\\n\" )", "delete posts and blogs before running this commend\\n\" ) sys.exit() categories = Category.objects.all()", "running this commend\\n\" ) sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories", "else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\")", "help = \"Deletes categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\"", "not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete:", "\"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if posts or blogs:", "**options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if posts or", "import sys from django.core.management.base import BaseCommand from cms.categories.models import Category from cms.posts.models import", "def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all()", "= Post.objects.all() blogs = Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please delete", "Please delete posts and blogs before running this commend\\n\" ) sys.exit() categories =", "categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length))", "= len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete() categories_length", "Post from cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes categories (bulk action)\"", "cms.posts.models import Post from cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes categories", "class Command(BaseCommand): help = \"Deletes categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove", "*args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if posts", "Blog class Command(BaseCommand): help = \"Deletes categories (bulk action)\" def handle(self, *args, **options):", "and blogs before running this commend\\n\" ) sys.exit() categories = Category.objects.all() if not", "is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in", "import Blog class Command(BaseCommand): help = \"Deletes categories (bulk action)\" def handle(self, *args,", "sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length", "BaseCommand from cms.categories.models import Category from cms.posts.models import Post from cms.blogs.models import Blog", "sys from django.core.management.base import BaseCommand from cms.categories.models import Category from cms.posts.models import Post", "\"⚠️ Please delete posts and blogs before running this commend\\n\" ) sys.exit() categories", "this commend\\n\" ) sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is", "Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category", "Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories", "posts or blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs before running this", "\"Deletes categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts =", "cms.categories.models import Category from cms.posts.models import Post from cms.blogs.models import Blog class Command(BaseCommand):", "import BaseCommand from cms.categories.models import Category from cms.posts.models import Post from cms.blogs.models import", "django.core.management.base import BaseCommand from cms.categories.models import Category from cms.posts.models import Post from cms.blogs.models", "posts = Post.objects.all() blogs = Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please", "delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete() categories_length -= 1 sys.stdout.write(\"\\n✅ Complete\\n\")", "commend\\n\" ) sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\")", "from cms.categories.models import Category from cms.posts.models import Post from cms.blogs.models import Blog class", "= Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories)", "if posts or blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs before running", "posts and blogs before running this commend\\n\" ) sys.exit() categories = Category.objects.all() if", "blogs before running this commend\\n\" ) sys.exit() categories = Category.objects.all() if not categories.count():", "from django.core.management.base import BaseCommand from cms.categories.models import Category from cms.posts.models import Post from", "Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️ Please delete posts and blogs before", "handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if", "to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete() categories_length -= 1 sys.stdout.write(\"\\n✅", "import Category from cms.posts.models import Post from cms.blogs.models import Blog class Command(BaseCommand): help", ") sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅ Categories is empty\\n\") else:", "action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs =", "import Post from cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes categories (bulk", "sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete() categories_length -= 1", "from cms.posts.models import Post from cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes", "cms.blogs.models import Blog class Command(BaseCommand): help = \"Deletes categories (bulk action)\" def handle(self,", "categories (bulk action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all()", "empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories:", "before running this commend\\n\" ) sys.exit() categories = Category.objects.all() if not categories.count(): sys.stdout.write(\"✅", "categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete()", "sys.stdout.write(\"✅ Categories is empty\\n\") else: categories_length = len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for", "Category from cms.posts.models import Post from cms.blogs.models import Blog class Command(BaseCommand): help =", "first\"\"\" posts = Post.objects.all() blogs = Blog.objects.all() if posts or blogs: sys.stdout.write( \"⚠️", "sys.stdout.write( \"⚠️ Please delete posts and blogs before running this commend\\n\" ) sys.exit()", "(bulk action)\" def handle(self, *args, **options): \"\"\"remove categories first\"\"\" posts = Post.objects.all() blogs", "len(categories) sys.stdout.write(\"Categories to delete: {}\\n\".format(categories_length)) for category in categories: sys.stdout.write(\"-\") category.delete() categories_length -=" ]
[ "servable view of a Panel application with a dialog\"\"\" from .app import view", "a servable view of a Panel application with a dialog\"\"\" from .app import", "<filename>application/pages/dialog_template/__init__.py \"\"\"Provides a servable view of a Panel application with a dialog\"\"\" from", "\"\"\"Provides a servable view of a Panel application with a dialog\"\"\" from .app" ]
[ "portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\")", "def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There are no transactions\" operations_df", "-> pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction = transactions[0].date historical_rates_date =", "rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid()", "= pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df =", "value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid()", "pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"]", "_create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There are no transactions\" operations_df =", "self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\")", "operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] *", "Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame:", "operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df,", "operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df", "y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self,", "= ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] -", "def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical", "= operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"]", "assert transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\",", "= ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df def", "operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self,", "pd from app.requester import ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester =", "-> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout()", "return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] =", "return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There are no", "list) -> pd.DataFrame: assert transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df", "y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations:", "operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def", "transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def", "transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df,", "ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions)", "plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55)", "= self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid()", "def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] =", "operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100", "\"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df", "def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert", "pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\")", "plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45)", "100 return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There are", "transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\",", "operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"]", "None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show()", "return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45)", "plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) ->", "operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There are no transactions\"", "[PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\")", "on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None:", "operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] )", "matplotlib.pyplot as plt import pandas as pd from app.requester import ExchangeRateRequester class Grapher:", "operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df def _create_operations_df(self, transactions: list) ->", "-> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] =", "operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"]", "run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\")", "def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical", "first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df", "plt import pandas as pd from app.requester import ExchangeRateRequester class Grapher: def __init__(self)", "as plt import pandas as pd from app.requester import ExchangeRateRequester class Grapher: def", "pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] =", "plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame)", "pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"]", "transactions: list) -> pd.DataFrame: assert transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions)", "[PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\")", "def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction =", "import pandas as pd from app.requester import ExchangeRateRequester class Grapher: def __init__(self) ->", "plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations:", "/ operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df def _create_operations_df(self, transactions: list)", "\"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def", "self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\")", "operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = (", "how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\",", "operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"]", "= operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"]", "transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df", "-> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There", "historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\")", "transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) ->", "no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df =", "__init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions,", "= pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"]", "assert transactions, \"There are no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df", "pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df)", "operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] /", "( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1", "= transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod", "* 100 return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions, \"There", "def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical", "= self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\",", "plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\")", "= self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame)", "from app.requester import ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester()", "self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are no", "transactions) -> pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction = transactions[0].date historical_rates_date", "pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout()", "= operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = (", "plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) ->", ") operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return", "_create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction = transactions[0].date", "None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def", ") * 100 return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert transactions,", "pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame)", "-> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show()", "historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum()", "pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction)", "no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"])", "= operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] =", "historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame:", "are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df", "columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"]) operations_df = pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return", "ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are no transactions\" first_transaction", "-> pd.DataFrame: assert transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df =", "import matplotlib.pyplot as plt import pandas as pd from app.requester import ExchangeRateRequester class", "\"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions, columns=[\"date\", \"transaction[+/-]\", \"transaction_rate\"])", "operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical portfolio profit", "pandas as pd from app.requester import ExchangeRateRequester class Grapher: def __init__(self) -> None:", "transactions, \"There are no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df =", "1 ) * 100 return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame: assert", "plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates", "( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df def _create_operations_df(self,", "= pd.merge(operations_df, transactions_df, on=\"date\", how=\"outer\") calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates:", "plt.ylabel(\"value\") plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None:", "* operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] = ( operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"]", "plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame)", "operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"]", "\"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"]", "plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None:", "import ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self,", "None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical portfolio profit [%]\") plt.tight_layout() plt.show()", "plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\")", "transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return", "* operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) *", "calculated_operations_df = self.run_calculations(operations_df) return calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\")", "plt.title(\"Historical portfolio value [PLN]\") plt.tight_layout() plt.show() def plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\",", "plot_profit(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical portfolio", "- 1 ) * 100 return operations_df def _create_operations_df(self, transactions: list) -> pd.DataFrame:", "class Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) ->", "calculated_operations_df def plot_historical_rates(self, historical_rates: pd.DataFrame) -> None: historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\")", "historical_rates.plot(x=\"date\", y=\"rate\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self,", "app.requester import ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester = ExchangeRateRequester() def", "as pd from app.requester import ExchangeRateRequester class Grapher: def __init__(self) -> None: self.exchange_rate_requester", "@staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"]", "-> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical portfolio profit [%]\") plt.tight_layout()", "None: self.exchange_rate_requester = ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are", "operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] * operations_df[\"rate\"] operations_df[\"value_pln_after_transaction\"] =", "operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 ) * 100 return operations_df def _create_operations_df(self, transactions:", "pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"profit\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=45) plt.ylabel(\"profit\") plt.title(\"Historical portfolio profit [%]\")", "columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) -> pd.DataFrame: operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0)", "self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df: pd.DataFrame) ->", "plt.ylabel(\"rate\") plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\",", "operations_df[\"transaction[+/-]\"] = operations_df[\"transaction[+/-]\"].fillna(0) operations_df[\"portfolio_value\"] = operations_df[\"transaction[+/-]\"].cumsum() operations_df[\"transaction_rate\"] = operations_df[\"transaction_rate\"].fillna(method=\"backfill\") operations_df[\"value_pln_temp\"] = operations_df[\"portfolio_value\"] *", "\"There are no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()),", "historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\", \"rate\"]) return historical_rates_df @staticmethod def run_calculations(operations_df:", "pd.DataFrame: assert transactions, \"There are no transactions\" operations_df = self._create_historical_rates_df(transactions) transactions_df = pd.DataFrame(transactions,", "operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio value", "are no transactions\" first_transaction = transactions[0].date historical_rates_date = self.exchange_rate_requester.get_historical_bids(first_transaction) historical_rates_df = pd.DataFrame(list(historical_rates_date.items()), columns=[\"date\",", "plt.title(\"Historical rates [PLN]\") plt.tight_layout() plt.show() def plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\")", "plot_portfolio_value_pln(self, operations: pd.DataFrame) -> None: operations.plot(x=\"date\", y=\"value_pln_temp\") plt.grid() plt.xlabel(\"date\") plt.xticks(rotation=55) plt.ylabel(\"value\") plt.title(\"Historical portfolio", "operations_df[\"portfolio_value\"] * operations_df[\"transaction_rate\"] ) operations_df[\"profit\"] = ( operations_df[\"value_pln_temp\"] / operations_df[\"value_pln_after_transaction\"] - 1 )", "= ExchangeRateRequester() def _create_historical_rates_df(self, transactions) -> pd.DataFrame: assert transactions, \"There are no transactions\"" ]
[ "doc_file_hash_mapper = [] already_seen = set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name", "1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1 updated_file_name =", "\"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen( f\"unzip -jo", "\"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml", "pathlib import Path import re import subprocess import tqdm import pandas as pd", "-l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name =", "[] already_seen = set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name result =", "= f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not match the file", "print(f\"{file_name} did not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name),", "Path import re import subprocess import tqdm import pandas as pd files =", "subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() )", "updated_file_name in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is", "= [] already_seen = set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name result", "tqdm import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper", "for file_name in tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip -l", "{ \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen( f\"unzip", "subprocess import tqdm import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\"))", "set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip", "file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result", "( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame", "} ) result = ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\",", ".communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name", "import re import subprocess import tqdm import pandas as pd files = (", "shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\",", "in tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True,", "file_name in tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\",", "-d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess .Popen( f\"mv", "updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not match the", "str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in", "subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0]))", "version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did", "not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\"", "from pathlib import Path import re import subprocess import tqdm import pandas as", "is None: print(f\"{file_name} did not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( {", "import subprocess import tqdm import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) +", "doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen(", "already_seen = set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name result = (", "content_file_name = match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen:", "version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1", "{file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1)", "= ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match =", "-jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = (", "as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen", "match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\"", "= 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1 updated_file_name", "f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d", "+ list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set() for file_name in tqdm.tqdm(files):", "os from pathlib import Path import re import subprocess import tqdm import pandas", "doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE )", "biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml", ".communicate() ) rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE )", "tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE", "rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() )", "= ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set() for", "re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name", "import tqdm import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) )", "= re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while", "already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name}", "= file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate()", "match is None: print(f\"{file_name} did not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append(", "{file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess", "the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } )", "match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version +=", "= set() for file_name in tqdm.tqdm(files): doc_hash = file_name.name result = ( subprocess.Popen(", "<reponame>danich1/annorxiver import os from pathlib import Path import re import subprocess import tqdm", ") .communicate() ) rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE", "list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set() for file_name in tqdm.tqdm(files): doc_hash", "1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not match", "f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not match the file pattern", ".Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame .from_records(doc_file_hash_mapper) .to_csv(\"biorxiv_doc_hash_mapper.tsv\",", ".Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result", "= ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) (", "stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True,", "continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess", "import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper =", "result = ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE", "None: print(f\"{file_name} did not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\":", "updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\"", ") result = ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True,", "f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if", "+= 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not", "match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" }", "pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen =", "in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match is None:", "f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name", "= f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name)", "= match.group(1) version = 1 updated_file_name = f\"{content_file_name}_v{version}\" while updated_file_name in already_seen: version", "import os from pathlib import Path import re import subprocess import tqdm import", "content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result = ( subprocess .Popen(", "stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version =", "re import subprocess import tqdm import pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\"))", "( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate()", "str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = ( subprocess .Popen( f\"unzip -jo {file_name}", "shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version", "already_seen.add(updated_file_name) if match is None: print(f\"{file_name} did not match the file pattern [\\d]+\")", "f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame .from_records(doc_file_hash_mapper) .to_csv(\"biorxiv_doc_hash_mapper.tsv\", sep=\"\\t\",", "pandas as pd files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = []", "if match is None: print(f\"{file_name} did not match the file pattern [\\d]+\") continue", "f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE ) .communicate() ) rename_result =", "biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame .from_records(doc_file_hash_mapper) .to_csv(\"biorxiv_doc_hash_mapper.tsv\", sep=\"\\t\", index=False)", ") match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1 updated_file_name =", "( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set() for file_name", ") .communicate() ) match = re.search(r'content/([\\d]+)\\.xml', str(result[0])) content_file_name = match.group(1) version = 1", "result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match", ") rename_result = ( subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate()", "( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() ) match = re.search(r'content/([\\d]+)\\.xml',", "list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set() for file_name in", "= ( subprocess .Popen( f\"unzip -jo {file_name} content/{content_file_name}.xml -d biorxiv_articles/.\", shell=True, stdout=subprocess.PIPE )", "while updated_file_name in already_seen: version += 1 updated_file_name = f\"{content_file_name}_v{version}\" already_seen.add(updated_file_name) if match", "file_name.name result = ( subprocess.Popen( f\"unzip -l {file_name}\", shell=True, stdout=subprocess.PIPE ) .communicate() )", ") doc_file_hash_mapper = [] already_seen = set() for file_name in tqdm.tqdm(files): doc_hash =", "biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame .from_records(doc_file_hash_mapper) .to_csv(\"biorxiv_doc_hash_mapper.tsv\", sep=\"\\t\", index=False) )", "[\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result = (", "did not match the file pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\":", "pattern [\\d]+\") continue doc_file_hash_mapper.append( { \"hash\": str(file_name), \"doc_number\": f\"{updated_file_name}.xml\" } ) result =", "import Path import re import subprocess import tqdm import pandas as pd files", "subprocess .Popen( f\"mv biorxiv_articles/{content_file_name}.xml biorxiv_articles/{updated_file_name}.xml\", shell=True, stdout=subprocess.PIPE ) .communicate() ) ( pd.DataFrame .from_records(doc_file_hash_mapper)", "files = ( list(Path(\"Back_Content\").rglob(\"*.meca\")) + list(Path(\"Current_Content\").rglob(\"*.meca\")) ) doc_file_hash_mapper = [] already_seen = set()" ]
[ "no answers, considering all answers received\" self.log.info(m) break if max_page_count and page_count >=", "to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on value. Defaults to:", "(:obj:`int`, optional): Get N number of clients at a time from the API.", "= \"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj", "\".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the", "group sensors defined, not mapping group params\" self.log.debug(m) return for group_filter in group.filters", "received_rows += page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m =", "row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args)", "max age property of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have", "\".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False,", "this question in XML format using server side export. Args: export_id (:obj:`str`): An", "= \"Finished mapping parameters for groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values)", "= \"Received expected row_count {c}, considering all answers received\" m = m.format(c=data.row_count) self.log.info(m)", "\"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"},", "cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "= True returns dict. Otherwise, return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs)", "mapping group params\" self.log.debug(m) return if not group_sensors: m = \"No question group", "\"\"\"Get a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated from. Defaults", "[ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())),", "= 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"]", "= datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt)", "return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N number of clients", "poll_total (:obj:`int`, optional): If not 0, wait until N clients have total instead", "Args: leading (:obj:`str`, optional): Prepend this text to each line. Defaults to: \"\".", "[\"Started Server Side for CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m =", "\"\"\"Get the answers for this question in XML format using server side export.", "self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args)", "\"{}\") params = param_defs.get(\"parameters\", []) for p in params: pdef = p.get(\"defaultValue\", \"\")", "value for this sensor. Args: key (:obj:`str`): Key name of parameter to set.", "\"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args:", "Server Side for CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id)", "datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received initial answers:", "id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for", "\"Picking first matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err =", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults", "datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs", "{now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\",", ":obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"]", "export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs: rest of", "filter being the only item in it. Defaults to: None. Returns: :obj:`Clients` \"\"\"", "None)) for attr in attrs] bits += [atmpl(k=k, v=v) for k, v in", "import time from collections import OrderedDict from . import exceptions from .. import", "value in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`,", "params(self): \"\"\"Get the parameters that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList", "leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result() self.refetch() def", "= utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter self._result = result self._last_result", "rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the API keep the cache_id", "return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] =", "= {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r", "= True cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if", "use for this workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`:", "Defaults to: 0. max_poll_count (:obj:`int`, optional): If not 0, only poll N times.", "an exception. Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if", "until for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs)", "(:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`,", "sensor.parameter_definition: m = \"No parameters defined on sensor {s}, going to next\" m", "optional): Ignore case when filtering on value. Defaults to: True. not_flag (:obj:`bool`, optional):", "export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows if possible (single line in", "page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for this", "= self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas = datas data =", "the parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k", "= self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else:", "Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True", "select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects =", "m = \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] ==", "self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result() self.refetch() def add_left_sensor( self, sensor,", "in params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\",", "index is None and there is no exact match, pick the first parse", "cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing", "= \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj,", ":obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\": now_dt,", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes", "True returns dict. Otherwise, return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"]", "err = [err, \"Supply an index of a parsed result:\", self.result_indexes] err =", "\"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if", "answers until for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos =", "6, # e.g. \"2 years, 3 months, 18 days, 4 hours, 22 minutes:", "= self.expiration[\"expiration\"] m = \"Start polling loop for answers until for {o} until", "Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj", "m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF format\",", "= row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows =", "to map\" self.log.debug(m) return m = \"Now mapping parameters for group filter: {gf}\"", "until a page returns no answers or the expected row count is hit.", "return self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a", "max_row_count are 0, fetch pages until a page returns no answers or the", "based on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq =", "(:obj:`int`): id of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to:", "for param in self.params: if param.value in [\"\", None] and not allow_empty_params: m", "lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object by id.", "answers received\" m = m.format(c=data.row_count) self.log.info(m) break if not page_rows: m = \"Received", "e=export_id) self.log.info(m) data = r.text if \"xml\" in export_id and (return_dict or return_obj):", "now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td,", "lvl=\"info\"): \"\"\"Get a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "= self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def ask(self, **kwargs): \"\"\"Ask the", "break if status[\"status\"] == \"failed\": m = \"Server Side Export failed: {status}\" m", "cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter definitions for this", "the last_registration filter being the only item in it. Defaults to: None. Returns:", "then add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr", "the parameters that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object", "set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined, and no value is set,", "a parameters value for this sensor. Args: key (:obj:`str`): Key name of parameter", "as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj = True returns", "operator. Defaults to: 1000. filters (:obj:`object`, optional): If a CacheFilterList object is supplied,", "large data sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object", "cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor", "be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have", "self._params = self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True", "of the filter for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value,", "m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end", "[]) for p in params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\")", "__repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return", "= result datas = result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] =", "left hand side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects", "= ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else:", "count {c}, considering all clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count +=", "True. hashes (:obj:`bool`, optional): Have the API include the hashes of rows values", "m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a", "= pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj,", "self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def ask(self, **kwargs): \"\"\"Ask the question.", "utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj", "and gets all clients in one call. Defaults to: 1000. max_page_count (:obj:`int`, optional):", "ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] =", "question has already been asked (id is set), we wipe out attrs: [\"id\",", ":obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check", "on this value. operator (:obj:`str`, optional): Operator to use for filter_value. Must be", "\"\"\" param_def = self.params_defined.get(key, None) if param_def is None: m = \"Parameter key", "): \"\"\"Start up a server side export for CSV format and get an", "get all pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch up to", "\"Supply an index of a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err)", "count: {c}\", ] m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info,", "self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns:", "m = \"Received {n} parse results (any exact match: {ac})\" m = m.format(n=len(result_obj),", "self.log.info(m) all_rows = data.rows page_count = 1 page_rows = all_rows while True: if", "level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion`", "False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use", "lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\" data", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log =", "this is None, a new CacheFilterList will be created with the last_registration filter", "params) @property def param_values(self): \"\"\"Get all of the parameter key and values. Returns:", "ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value == \"\":", "optional): If not 0, only poll N times. Defaults to: 0. **kwargs: rest", "or []) >= data.row_count: m = \"Received expected row_count {c}, considering all answers", "that have registered in N number of seconds. Defaults to: 300. operator (:obj:`str`,", "sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor`", "created on initial get answers page alive for N seconds. Defaults to: 900.", "to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that are not in the", "Throws exception if False and key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\"", "in self.params_defined: if key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param", "lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result =", "of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value", "= self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos =", "result m = [\"Received Server Side Export start response for CSV format\", \"code={c}\"]", "defined on sensor {s}, going to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id", "or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse result indices in", "use_first=False, **kwargs): \"\"\"Pick a parse result and ask it. Args: index (:obj:`int`, optional):", "object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects class", "name (:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults", "return_dict = True returns dict. Otherwise, return str. \"\"\" self._check_id() client_args = {}", "filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result", "@property def get_canonical(self): \"\"\"Return any parse result that is an exact match.\"\"\" for", "{s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters", "\"2 years, 3 months, 18 days, 4 hours, 22 minutes: # 'TimeDiff', and", "be before we consider it invalid. 0 means to use the max age", "and 3.67 seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7,", "all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt:", "adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas =", "if max_page_count and page_count >= max_page_count: m = \"Reached max page count {c},", "from __future__ import division from __future__ import print_function from __future__ import unicode_literals import", "= pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for", "workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result", "cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result", "m = \"No question group sensors defined, not mapping group params\" self.log.debug(m) return", "\"No index supplied\", \"no exact matching parsed result\", \"and use_first is False!\", ]", "type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters", "sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the left hand side of", "for this question. Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`:", "each page to fetch at a time. Defaults to: 1000. max_page_count (:obj:`int`, optional):", "# SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3", "ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True", "{this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m = \", \".join(m) m =", "format, return a dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional): If export_id", "obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "= m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for XML", "pick the first parse result and ask it. **kwargs: rest of kwargs: Passed", "datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get", "for CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return", "result infos = result() self._last_infos = infos m = \"Received answers info: {infos}\"", "in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value in", "XML format using server side export. Args: export_id (:obj:`str`): An export id returned", "obj in result_obj: yield obj if page_size: paging_get_args = {k: v for k,", "break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt}, considering all answers", "self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter for this sensor. Returns:", "self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for", "0. max_poll_count (:obj:`int`, optional): If not 0, only poll N times. Defaults to:", "Defaults to: True. hashes (:obj:`bool`, optional): Have the API include the hashes of", "if now_pct >= poll_pct: m = \"Reached {now_pct} out of {pct}, considering all", "If question has already been asked (id is set), we wipe out attrs:", "m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\",", "\".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end", "\"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\":", "attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in", "headers else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m", "self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] =", "2. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs:", "\"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m", "\"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get", "of {pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if", "\"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr,", "for N seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have the API include", "api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\")", "this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None.", "{gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for x", "m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total =", "as None sometimes # need to refetch data for N retries if that", "(:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5. max_poll_count (:obj:`int`,", "one API response. For large data sets of answers, this is unwise. Returns:", "invalid. 0 means to use the max age property of the sensor. Defaults", "0 means to use the max age property of the sensor. Defaults to:", "(:obj:`bool`, optional): If sensor has parameters defined, and no value is set, try", "m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups or []:", "= self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side Export start response", "\"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\":", "m = [\"Started Server Side for CSV format\", \"export_id={e!r}\"] m = \", \".join(m)", "= all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select", "ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"]", "datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] =", "filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter,", "this sensor to be used in a question. Args: value (:obj:`str`): Filter sensor", "\"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter,", "and poll_total <= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count =", "bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits)", "\"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv(", "for CEF format and get an export_id. Args: leading (:obj:`str`, optional): Prepend this", "\"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\":", "SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI", "= self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count and poll_count >= max_poll_count:", "time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "0. cache_expiration (:obj:`int`, optional): Have the API keep the cache_id that is created", "data for N retries if that happens page_datas = page_result() self._last_datas = page_datas", "export id returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns:", "to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\",", "\"\"\"Return the ResultInfo for this question. Args: **kwargs: rest of kwargs: Passed to", "was generated from. Defaults to: None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self,", "getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None)", "of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj =", "\"No more parameter values left to map\" self.log.debug(m) return m = \"Now mapping", "in params) @property def param_values(self): \"\"\"Get all of the parameter key and values.", "m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed", "if not group_sensors: m = \"No question group sensors defined, not mapping group", "pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and ask it. Args:", "whole=this_total) m = [ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out of", "\"\"\"Get a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0,", "it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs:", "has already been asked (id is set), we wipe out attrs: [\"id\", \"context_group\",", "m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas return datas def answers_get_data_paged( self,", "v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls,", "datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result =", "ret = OrderedDict() for k in self.params_defined: ret[k] = \"\" for p in", "return if not group_sensors: m = \"No question group sensors defined, not mapping", "\"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show", "\"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"]", "considering all clients fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows:", "to use for this workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns:", "result=result) @property def params_defined(self): \"\"\"Get the parameter definitions for this sensor. Notes: Will", "self._filter @property def filter_vals(self): \"\"\"Get the key value pairs of the filter for", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name (:obj:`str`): Name of sensor", "\"\" for p in self.params: ret[p.key] = p.value return ret @property def params(self):", "def filter_vals(self): \"\"\"Get the key value pairs of the filter for this sensor.", "self._last_result = result self.obj = result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False", "\"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers:", "on initial get answers page alive for N seconds. Defaults to: 900. hashes", "\".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\" in export_id", "{ \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC", "question. Args: poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to:", "m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get", "{d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m = \", \".join(m)", "m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result", "result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def ask(self, **kwargs): \"\"\"Ask", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging,", "row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start", "Notes: If question has already been asked (id is set), we wipe out", "to use for this workflow. id (:obj:`int`): id of sensor to fetch. lvl", "max_page_count and page_count >= max_page_count: m = \"Reached max page count {c}, considering", "in [\"\", None]: derived_default = pval elif pvals: derived_default = pvals[0] else: derived_default", "filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore", "**kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "Args: poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5.", "\", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\" in", "if x.id == sensor_id][0] if not sensor.parameter_definition: m = \"No parameters defined on", "\"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor =", "\"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs] bits +=", "= \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id,", "in [\"\", None] and not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is", "any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ]", "= \"Received {n} parse results (any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical)", "put before and after parameter key name when sending to API. Defaults to:", "def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a server side", "\"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj,", "return a dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional): If export_id is", "Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\"", "object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj", "{c}\", \"status {status}\", ] m = \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m)", "(:obj:`str`, optional): Have filter consider the value type as this. Must be one", "group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not group: m = \"Empty group,", "info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)),", "max_row_count: m = \"Hit max pages of {max_row_count}, considering all answers received\" m", "optional): Have filter match all values instead of any value. Defaults to: False.", "Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data(", "adapter, id, lvl=\"info\"): \"\"\"Get a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "{c}, considering all clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count += 1", "\"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1,", "): \"\"\"Get the answers for this question in XML format using server side", "Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that are not in", "all answers in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or", "data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received initial answers: {d.rows}\", \"expected row_count:", "pdef not in [\"\", None]: derived_default = pdef elif pval not in [\"\",", "\"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter =", ":obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor", "= \"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def", "(:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to", "(:obj:`str`): An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is", "parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in", "for this question. Args: poll_sleep (:obj:`int`, optional): Check for answers every N seconds.", "self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all answers in\"", "if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must", "parameter values left to map\" self.log.debug(m) return m = \"Now mapping parameters for", "from .. import results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor.", "groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs)", "value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for this sensor. Args:", "sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count", "if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\",", "from collections import OrderedDict from . import exceptions from .. import utils from", "= is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt", "\"poll count: {c}\", ] m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct),", "m = [ \"Server Side Export completed\", \"reached max poll count {c}\", \"status", "not in the parameters definition for this sensor to be set. Throws exception", "Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0, fetch pages until", "Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args = {}", "= datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter(", "# need to refetch data for N retries if that happens page_datas =", "Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def", "or []: if not param_values: m = \"No more parameter values left to", "or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB", "each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params", "one of the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m)", "filters to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash", "have total instead of ``estimated_total`` of clients from API. Defaults to: 0. max_poll_count", "out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m = \", \".join(m)", "def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of filters", "the status for this questions server side export. Args: export_id (:obj:`str`): An export", "parameter values left to map\" self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition:", "form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl", "m = \"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow", "API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", "optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj``", "row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj = result()", "gets all clients in one call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only", "self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question. Args: **kwargs:", "poll_count >= max_poll_count: m = [ \"Server Side Export completed\", \"reached max poll", "optional): Only fetch up to this many rows. Defaults to: 0. cache_expiration (:obj:`int`,", "\"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\",", "(:obj:`bool`, optional): Have the API include the hashes of rows values. Defaults to:", "include the hashes of rows values Defaults to: False. sleep (:obj:`int`, optional): Wait", "e.g. 125MB or 23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\":", "question. Args: hashes (:obj:`bool`, optional): Have the API include the hashes of rows", "XML format, return a dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional): If", "self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt", "= result.object_obj[\"export_id\"] m = [\"Started Server Side for XML format\", \"export_id={e!r}\"] m =", "= datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m =", "filters on the right hand side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors", "workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined, and no value", "expiration details for this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td =", "None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this", "self.obj[0] m = \"Picking first matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m)", ":meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in", "API object \"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor()", "not use any paging, which means ALL answers will be returned in one", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] =", "m = \"Picking parsed question based on exact match: {pq.question}\" m = m.format(pq=pq)", "data sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\"", "log.info(m) break page_count += 1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result =", "exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj]) m = \"Received {n} parse", "ask it. Args: index (:obj:`int`, optional): Index of parse result to ask. Defaults", "max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an iterator. Args:", "= m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList()", "p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef not in [\"\", None]: derived_default", "filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\",", "= obj self.adapter = adapter self._result = result self._last_result = result def __repr__(self):", "optional): Have filter consider the value type as this. Must be one of", "= hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side", "0. cache_expiration (:obj:`int`, optional): When page_size is not 0, have the API keep", "\"Picking parsed question based on index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m)", "\"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"]", "adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result =", "page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod", "adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0,", "answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration", "expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start", "Side for XML format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m)", "page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch errors where API", "= result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF format\", \"export_id={e!r}\"] m =", "pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical m = \"Picking parsed", "not page_rows: m = \"Received a page with no answers, considering all answers", "json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for p in params: pdef =", "match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return x return None def map_select_params(self,", "'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\":", "= [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else False),", "result = adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\",", "\"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows,", "add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in", "adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients", "workflow. last_reg (:obj:`int`, optional): Only return clients that have registered in N number", "received\" self.log.info(m) break if max_page_count and page_count >= max_page_count: m = \"Reached max", "+= 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch errors", "= [\"Received Server Side Export start response for CSV format\", \"code={c}\"] m =", "\"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that", ":meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an XML format, return a dictionary", "= dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m = [ \"Received SSE status", "of the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or", "API return all rows that do not match the operator. Defaults to: 1000.", "infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this question. Args: hashes", "index is None and one of the parse results is an exact match,", "adapter self._result = result self._last_result = result def __repr__(self): \"\"\"Show object info. Returns:", "all clients in one call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch", "bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else", "len(paging_result_obj) received_rows += page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m", "= getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\",", "return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object", "\"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API", "or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls", "Defaults to: False. max_age_seconds (:obj:`int`, optional): How old a sensor result can be", "Allow parameter keys that are not in the parameters definition for this sensor", "to: True. \"\"\" param_def = self.params_defined.get(key, None) if param_def is None: m =", "workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return", "number of seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines how the last_registered", "result and ask it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question`", "0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True:", "server side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs:", "m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs):", "parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif", "m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct =", "start = datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt =", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are", "Server Side Export start response for XML format\", \"code={c}\"] m = \", \".join(m)", "to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If index is None and", "one page at a time. Args: page_size (:obj:`int`, optional): Size of each page", "def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for this", "optional): Wait N seconds between fetching each page. Defaults to: 5. **kwargs: rest", "optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`.", ".. import results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args:", "response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m = m.format(r=r, e=export_id)", "on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0]", "m = [\"Received Server Side Export start response for XML format\", \"code={c}\"] m", "= [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod", "in selects: if not param_values: m = \"No more parameter values left to", "object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined, and no value is", "if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0,", "select.sensor.hash = self.obj.hash select.WORKFLOW = self return select class Question(Workflow): def __str__(self): \"\"\"Show", "if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value == \"\": value", "considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m =", "mapping parameters for groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args", "result() def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging level.", "m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result =", "\"\"\"Add a sensor to the left hand side of the question. Args: sensor", "optional): Include column headers. Defaults to: True. hashes (:obj:`bool`, optional): Have the API", "max poll count {c}, considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break", "json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values: m = \"No more parameter", "m = \"Finished polling for Server Side Export in {dt}, {status}\" m =", "answers in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def", ">= max_page_count: m = \"Reached max page count {c}, considering all answers in\"", "Tanium API.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import", "last_registration filter generated by this method will be appended to it. If this", "optional): Have the API keep the cache_id that is created on initial get", "from the API. If 0, disables paging and gets all clients in one", "= pdef elif pval not in [\"\", None]: derived_default = pval elif pvals:", "(:obj:`object`, optional): If a CacheFilterList object is supplied, the last_registration filter generated by", "(:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow. lvl (:obj:`str`, optional): Logging level.", "result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data])", "= sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if filters", "Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter,", "None def map_select_params(self, pq): \"\"\"Map parameters to sensors on the left hand side", "object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id", "= \"No id issued yet, ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self):", "in export_id and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method,", "{d.estimated_total}\", ] m = \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows", "the match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How old a sensor result", "self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up", "group, not mapping group params\" self.log.debug(m) return if not group_sensors: m = \"No", "cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1 m =", "@classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text from", "we consider it invalid. 0 means to use the max age property of", "wait till error_count / no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", "Server Side Export start response for CSV format\", \"code={c}\"] m = \", \".join(m)", "= \"Server Side Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status", "hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas = datas", "= m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start", "result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result() self.refetch() def add_left_sensor(", "datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\",", "parameters value for this sensor. Args: key (:obj:`str`): Key name of parameter to", "ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging level. Defaults to:", "utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out", "this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [", "values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in self.params_defined: ret[k] =", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result", "m.format(c=data.row_count) self.log.info(m) break if not page_rows: m = \"Received a page with no", "is None: m = \"Parameter key {o!r} is not one of the defined", "a server side export for CEF format and get an export_id. Args: leading", ":meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every N", "cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end", "have the API keep the cache of clients for this many seconds before", "\"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"},", "optional): If set, negate the match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How", "(:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined, and", "= infos m = \"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self))", "**kwargs): \"\"\"Get parse results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "supplied\", \"no exact matching parsed result\", \"and use_first is False!\", ] err =", "is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params:", "to be used in a question. Args: value (:obj:`str`): Filter sensor rows returned", "value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor)", "\"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m", "= { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, #", "def params(self): \"\"\"Get the parameters that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`:", "result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id,", "cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False,", "99. poll_secs (:obj:`int`, optional): If not 0, wait until N seconds for pct", "= adapter self._result = result self._last_result = result def __repr__(self): \"\"\"Show object info.", "return self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object", "): \"\"\"Add a sensor to the left hand side of the question. Args:", "every N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until the percentage", "= p.value return ret @property def params(self): \"\"\"Get the parameters that are set", "[]), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server", ":obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"]", "data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl =", "use any paging, which means ALL answers will be returned in one API", "sensor {s}, going to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id", "page_rows = all_rows while True: if len(all_rows or []) >= data.row_count: m =", "stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total =", "to each line. Defaults to: \"\". trailing (:obj:`str`, optional): Append this text to", "index supplied\", \"no exact matching parsed result\", \"and use_first is False!\", ] err", "status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m = \"Server Side Export completed:", "this workflow. name (:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`, optional): Logging", "generated from. Defaults to: None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl)", "None sometimes # need to refetch data for N retries if that happens", "0. poll_total (:obj:`int`, optional): If not 0, wait until N clients have total", "clients total instead of until question expiration. Defaults to: 0. poll_total (:obj:`int`, optional):", "\"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for", "infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct} out of", "1 page_rows = all_rows while True: if len(all_rows or []) >= data.row_count: m", "= \"SSE get data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return", "Adapter to use for this workflow. text (:obj:`str`): Question text to parse. lvl", "\"\"\"Get the status for this questions server side export. Args: export_id (:obj:`str`): An", "result m = [\"Received Server Side Export start response for XML format\", \"code={c}\"]", "iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters (:obj:`object`, optional):", "key for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or", "c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this", "self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not group: m = \"Empty", "seconds between fetching each page. Defaults to: 5. **kwargs: rest of kwargs: Passed", "break if not page_rows: m = \"Received a page with no answers, considering", "hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side Export", "Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index] m = \"Picking parsed question", "the only item in it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict =", "\"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name),", "operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod", "for this sensor to be used in a question. Args: value (:obj:`str`): Filter", "obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has been asked by seeing", "/ no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start", "need to refetch data for N retries if that happens page_datas = page_result()", "pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch up to this many", "a new CacheFilterList will be created with the last_registration filter being the only", "\"No id issued yet, ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get", "lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by", "= result self.obj = result() def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl", "paging, which means ALL answers will be returned in one API response. For", "= m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or []) >= max_row_count: m", "= self.obj[index] m = \"Picking parsed question based on index {index}: {pq.question}\" m", "not group_sensors: m = \"No question group sensors defined, not mapping group params\"", "last_reg (:obj:`int`, optional): Only return clients that have registered in N number of", "self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos = infos", "\"\"\"Pick a parse result and ask it. Args: index (:obj:`int`, optional): Index of", "= self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading", "\"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse result that is an exact", "m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for groups,", "= \"Reached max page count {c}, considering all answers in\" m = m.format(c=max_page_count)", "self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all answers in\" m = m.format(expiration=self.expiration)", "optional): Have the API include the hashes of rows values Defaults to: False.", "{index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq =", "in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is invalid, must be one", "last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of filters to be used", "Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id)", "export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export for completion. Args: export_id", "in group.filters or []: if not param_values: m = \"No more parameter values", "Prepend this text to each line. Defaults to: \"\". trailing (:obj:`str`, optional): Append", "info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\",", "Args: index (:obj:`int`, optional): Index of parse result to ask. Defaults to: None.", "(:obj:`int`, optional): If not 0, wait until N clients have total instead of", "and not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\"", "using server side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`.", "= adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if filters is not None:", "kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count =", "or :obj:`dict` or :obj:`str`: If return_obj = True returns ResultSetList ApiModel object. If", "return sensor = select.sensor if not sensor.parameter_definition: m = \"No parameters defined on", "(:obj:`int`, optional): Wait until the percentage of clients total is N percent. Defaults", "id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an XML format,", "\"Received {n} parse results (any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m)", "if max_poll_count and poll_count >= max_poll_count: m = [ \"Server Side Export completed\",", "23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10,", "def filter(self): \"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object", "or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow()", "have registered in N number of seconds. Defaults to: 300. operator (:obj:`str`, optional):", "= not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self,", "= m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj]) m =", "the parameter definitions for this sensor. Notes: Will try to resolve a default", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked (id", "not 0, only poll N times. Defaults to: 0. **kwargs: rest of kwargs:", "data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data =", "cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter,", "self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls =", "bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__)", "return x return None def map_select_params(self, pq): \"\"\"Map parameters to sensors on the", "\"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\":", "ResultInfoList API object \"\"\" # TODO: Add wait till error_count / no_results_count ==", "\"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self,", "get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag", "= m.format(c=data.row_count) self.log.info(m) break if not page_rows: m = \"Received a page with", "this many seconds before expiring the cache. Defaults to: 600. sleep (:obj:`int`, optional):", "\"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if", "to sensors on the left hand side of the question.\"\"\" param_cls = self.api_objects.Parameter", "page at a time. Args: page_size (:obj:`int`, optional): Size of each page to", ":obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args", "\"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0,", "format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def", "\"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys] else:", "= datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"]", "= \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p in params) @property", "Export completed: {status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m", "and max_row_count are 0, fetch pages until a page returns no answers or", "return all rows that do not match the operator. Defaults to: 1000. filters", "= datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True,", "until question expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If not 0, wait", "pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level,", "(numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or 23K or 34.2Gig", "= \"Picking first matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err", "{info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\", ] m", "group_filter.sensor.id sensor = [x for x in group_sensors if x.id == sensor_id][0] if", "OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must be one of {vo}\" m", "count {c}\", \"status {status}\", ] m = \", \".join(m) m = m.format(c=max_poll_count, status=status)", "m = \"New polling loop #{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m)", "Defaults to: None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj =", "for this workflow. last_reg (:obj:`int`, optional): Only return clients that have registered in", "not_flag (:obj:`bool`, optional): If set, negate the match. Defaults to: False. max_age_seconds (:obj:`int`,", "not in [\"\", None]: derived_default = pdef elif pval not in [\"\", None]:", "Otherwise, return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"]", "\" index: {idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list", "received_rows >= total_rows: m = \"Reached total rows count {c}, considering all clients", "\"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name,", "no value is set, try to derive the default value from each parameters", "filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600,", "and store it in \"derived_default\" key for each parameter definition returned. Returns: :obj:`collections.OrderedDict`", "answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this question. Args: hashes (:obj:`bool`, optional):", "N seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have the API include the", "to: True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is", "Defaults to: False. type (:obj:`str`, optional): Have filter consider the value type as", "filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`,", "not_flag=False, filters=None ): \"\"\"Build a set of filters to be used in :meth:`Clients.get_all.", "fetch up to this many pages. If 0, get all pages. Defaults to:", "if key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params:", "side of the question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional):", "info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for", "3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"]", "in str form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r}, params: {params}, exact:", "in result_obj]) m = \"Received {n} parse results (any exact match: {ac})\" m", "for this workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList", "id (:obj:`int`): id of question to fetch. lvl (:obj:`str`, optional): Logging level. Defaults", "{now_pct} out of {pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m)", "Get default value from parameter definition if value is \"\". Defaults to: True.", "max page count {c}, considering all answers in\" m = m.format(c=max_page_count) self.log.info(m) break", ":obj:`dict` or :obj:`str`: If return_obj = True returns ResultSetList ApiModel object. If return_dict", "= self.obj[0] m = \"Picking first matching parsed question: {pq.question}\" m = m.format(pq=pq)", "None, throw an exception. Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params", "API object \"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def", "get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache", "asked (id is set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add", "rows that do not match the operator. Defaults to: 1000. filters (:obj:`object`, optional):", "not match the operator. Defaults to: 1000. filters (:obj:`object`, optional): If a CacheFilterList", "considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >=", "for x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] =", "or return_dict and return_obj False, return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel`", "value and store it in \"derived_default\" key for each parameter definition returned. Returns:", "m = \"Finished getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows or []),", "\".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj:", "match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How old a sensor result can", "use for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`,", "and there is no exact match, pick the first parse result and ask", "self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m", "Check for answers every N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait", "self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total = est_total", "Ignore case when filtering on value. Defaults to: True. not_flag (:obj:`bool`, optional): If", "\".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"):", "p in params) @property def param_values(self): \"\"\"Get all of the parameter key and", "sub_group) @property def result_indexes(self): \"\"\"Get the parse result indices in str form.\"\"\" pq_tmpl", "= datetime.datetime.utcnow() elapsed = end - start m = \"Finished polling for Server", "m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical m = \"Picking", "is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start", "return_dict and return_obj False, return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size", "try to resolve a default value and store it in \"derived_default\" key for", "obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow):", "if possible (single line in each cell) Defaults to: False. headers (:obj:`bool`, optional):", "the value is not set, \"\", or None, throw an exception. Defaults to:", "\"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p in params) @property def", "= 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m =", "API include the hashes of rows values Defaults to: False. **kwargs: rest of", "(single line in each cell) Defaults to: False. headers (:obj:`bool`, optional): Include column", "self._last_result = result m = [\"Received Server Side Export start response for CEF", "= m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for", "Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {}", "a ResultSet object. Defaults to: True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`.", "m = [ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\",", "cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result", "N times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns:", "the Tanium API.\"\"\" from __future__ import absolute_import from __future__ import division from __future__", "status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m = m.format(r=r,", "result_obj is None: m = \"No parse results returned for text: {t!r}\" m", "from clients for this question. Args: poll_sleep (:obj:`int`, optional): Check for answers every", "until the percentage of clients total is N percent. Defaults to: 99. poll_secs", "= \"Operator {o!r} is invalid, must be one of {vo}\" m = m.format(o=operator,", "exceptions.ModuleError(m) elif derive_default and value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim =", "__future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime", "{k: v for k, v in get_args.items()} while True: if max_page_count and page_count", "is no exact match, pick the first parse result and ask it. **kwargs:", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text (:obj:`str`): Question text to parse.", "@classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object by id. Args:", "answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side export for XML format and", "True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received", "dict. Otherwise, return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\"", "sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that", "= {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count", "{o!r} is invalid, must be one of {vo}\" m = m.format(o=type, vo=list(TYPE_MAP.keys())) raise", "\"Reached max page count {c}, considering all clients fetched\" m = m.format(c=max_page_count) log.info(m)", "alive for N seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have the API", "the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter match all values", "m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\":", "for this workflow. name (:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`, optional):", "= datetime.datetime.utcnow() elapsed = end - start m = [ \"Finished polling in:", "age property of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter", "+= [atmpl(k=k, v=v) for k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits))", "start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes", "Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns:", "self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a server side export for", "= cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache =", "self.obj = obj self.adapter = adapter self._result = result self._last_result = result def", "for this workflow. id (:obj:`int`): id of question to fetch. lvl (:obj:`str`, optional):", "count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow()", "Defaults to: \"\". trailing (:obj:`str`, optional): Append this text to each line. Defaults", "format or return_dict and return_obj False, return the raw text as is. Returns:", "to use for this workflow. text (:obj:`str`): Question text to parse. lvl (:obj:`str`,", "__str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [", "Defaults to: 1000. filters (:obj:`object`, optional): If a CacheFilterList object is supplied, the", "index (:obj:`int`, optional): Index of parse result to ask. Defaults to: None. use_exact_match", "k in self.params_defined: ret[k] = \"\" for p in self.params: ret[p.key] = p.value", "self._last_result = result infos = result() self._last_infos = infos m = \"Received answers", "self.expiration[\"expiration\"] m = \"Start polling loop for answers until for {o} until {stop_dt}\"", "else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m =", "derived_default = pval elif pvals: derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"]", "values left to map\" self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition: m", ":meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format or return_dict and return_obj False,", "getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return", "method will be appended to it. If this is None, a new CacheFilterList", "set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for", "Adapter to use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to:", "@staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of", "ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt -", "self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in", "status[\"status\"] == \"completed\": m = \"Server Side Export completed: {status}\" m = m.format(status=status)", "\"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result()", "m = m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m = \"Server Side", "None] and not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is empty, definition:", "CSV rows if possible (single line in each cell) Defaults to: False. headers", "result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters", "{pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for", "key name when sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow", "returned in one API response. For large data sets of answers, this is", "Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus", "ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ):", "hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed = end", "optional): Prepend this text to each line. Defaults to: \"\". trailing (:obj:`str`, optional):", "XML format, return a ResultSet object. Defaults to: True. **kwargs: rest of kwargs:", "\"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m = \", \".join(m) m", "at a time from the API. If 0, disables paging and gets all", "cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait N seconds between fetching each", "\", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server", "unicode_literals import datetime import json import time from collections import OrderedDict from .", "info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)),", "pval = p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef not in [\"\",", "{infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0,", "filter generated by this method will be appended to it. If this is", "datetime.datetime.utcnow() elapsed = end - start m = \"Finished polling for Server Side", "for k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__)", "If this is None, a new CacheFilterList will be created with the last_registration", "1000. max_page_count (:obj:`int`, optional): Only fetch up to this many pages. If 0,", "seconds between fetching each page. Defaults to: 2. lvl (:obj:`str`, optional): Logging level.", "not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return", "created with the last_registration filter being the only item in it. Defaults to:", "sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\",", "\"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self,", "expected row_count {c}, considering all answers received\" m = m.format(c=data.row_count) self.log.info(m) break if", "def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "total rows count {c}, considering all clients fetched\" m = m.format(c=total_rows) log.info(m) break", "response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m = m.format(r=r, status=status)", "Add wait till error_count / no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs)", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", ":obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj = True returns ResultSetList ApiModel object.", "client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for", "page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end - start", "start = datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id", "self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for x in group_sensors if x.id", "0 row_count = page_size if filters is not None: get_args[\"cache_filters\"] = filters if", "all clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count += 1 row_start +=", "= \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def", "Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format or return_dict and", "= \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter,", "adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter definitions", "one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration", "side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects", "\"and use_first is False!\", ] err = \", \".join(err) err = [err, \"Supply", "m = [\"Received Server Side Export start response for CEF format\", \"code={c}\"] m", "dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m = [ \"Received SSE status response:", "return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter", "Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes:", "self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value in [\"\",", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args)", "sensor to be used in a question. Args: value (:obj:`str`): Filter sensor rows", "key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result()", "param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter for this", "refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj =", "(:obj:`int`, optional): Only return clients that have registered in N number of seconds.", "self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the", "clients: {d.estimated_total}\", ] m = \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows =", "the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not", "level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`:", "Notes: If max_page_count and max_row_count are 0, fetch pages until a page returns", "[]) >= data.row_count: m = \"Received expected row_count {c}, considering all answers received\"", "Side Export start response for XML format\", \"code={c}\"] m = \", \".join(m) m", "cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get", "= \"\" for p in self.params: ret[p.key] = p.value return ret @property def", "not 0, wait until N clients have total instead of ``estimated_total`` of clients", "(:obj:`int`, optional): Only fetch up to this many rows. Defaults to: 0. cache_expiration", "} TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\":", "\"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a", "self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for this question in", "group_filter in group.filters or []: if not param_values: m = \"No more parameter", "bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter", "Get N number of clients at a time from the API. If 0,", "self.log.info(m) break if max_row_count and len(all_rows or []) >= max_row_count: m = \"Hit", "Notes: Will try to resolve a default value and store it in \"derived_default\"", "adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get", "get answers page alive for N seconds. Defaults to: 900. hashes (:obj:`bool`, optional):", "break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m =", "{dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas return datas", "exact match, pick the first parse result and ask it. **kwargs: rest of", "m = \"Finished mapping parameters for selects, parameter values left: {pv!r}\" m =", "obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl =", "returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\"", "Side for CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m)", "self.obj: if x.question.from_canonical_text: return x return None def map_select_params(self, pq): \"\"\"Map parameters to", "@property def filter_vals(self): \"\"\"Get the key value pairs of the filter for this", "(:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated from. Defaults to: None. \"\"\"", "\"total_rows={total_rows}\", ] m = \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, )", "filter for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys", "exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return x return None def", "all_rows while True: if len(all_rows or []) >= data.row_count: m = \"Received expected", "answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m", "stop_dt {stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]:", "result_obj = result() if result_obj is None: m = \"No parse results returned", "\"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP", "an index of a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq)", "= len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id", "not XML format or return_dict and return_obj False, return the raw text as", "max_poll_count and poll_count >= max_poll_count: m = [ \"Server Side Export completed\", \"reached", "for x in self.obj: if x.question.from_canonical_text: return x return None def map_select_params(self, pq):", "m = \"Finished mapping parameters for groups, parameter values left: {pv!r}\" m =", "Have filter consider the value type as this. Must be one of :data:`TYPE_MAP`", "export_id. Args: hashes (:obj:`bool`, optional): Have the API include the hashes of rows", "True: poll_count += 1 m = \"New polling loop #{c} for {o}\" m", "select = self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined:", "\"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\",", "return TYPE_MAP[type] m = \"Type {o!r} is invalid, must be one of {vo}\"", "= [ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\",", "{} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r =", "answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg (:obj:`int`, optional): Only", "self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type", "cache_id that is created on initial get answers page alive for N seconds.", "row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m = \", \".join(m) m =", "self.log.info(m) break if status[\"status\"] == \"failed\": m = \"Server Side Export failed: {status}\"", "{c}, considering all clients fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows >=", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging, which means", "For large data sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API", "the operator. Defaults to: 1000. filters (:obj:`object`, optional): If a CacheFilterList object is", "= p.get(\"values\", []) if pdef not in [\"\", None]: derived_default = pdef elif", "out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs =", "up to this many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the", "self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for groups, parameter values left: {pv!r}\"", "ret[\"expire_in\"] = ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id()", "1 m = \"New polling loop #{c} for {o}\" m = m.format(c=poll_count, o=self)", "in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m", "lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result =", "None. use_exact_match (:obj:`bool`, optional): If index is None and one of the parse", "in answers: {info.row_count}\", \"poll count: {c}\", ] m = \", \".join(m) m =", "= result() self._last_infos = infos m = \"Received answers info: {infos}\" m =", "N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If not 0, only poll", "derived_default = pdef elif pval not in [\"\", None]: derived_default = pval elif", "def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object by id. Args: adapter", "derive the default value from each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`,", "+ datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop for answers", "\"Server Side Export completed: {status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"] ==", "\"\"\" if index: pq = self.obj[index] m = \"Picking parsed question based on", ":meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", "received\" m = m.format(c=data.row_count) self.log.info(m) break if not page_rows: m = \"Received a", "line. Defaults to: \"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`:", "= est_total if poll_total and poll_total <= est_total: this_total = poll_total now_pct =", "optional): Index of parse result to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional):", "set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for key", "self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question. Args: **kwargs: rest", "\"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\"", "in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg (:obj:`int`,", "sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the left hand side", "Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True", "for CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return", "= [x.strip().lower() for x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split))", "lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\",", "status[\"status\"] == \"failed\": m = \"Server Side Export failed: {status}\" m = m.format(status=status)", "status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data", "Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\"", "response. For large data sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList", "{c}, considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs)", "m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m = \"Reached {now_pct}", "clients for this question. Args: poll_sleep (:obj:`int`, optional): Check for answers every N", "question based on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq", "Question text to parse. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs:", "= \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m =", "self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped", "= \"No question group sensors defined, not mapping group params\" self.log.debug(m) return for", "of seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines how the last_registered attribute", "group params\" self.log.debug(m) return if not group_sensors: m = \"No question group sensors", "OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must be one of", "ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question", "self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set", "page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished", "\"\"\"Check that question has been asked by seeing if self.obj.id is set.\"\"\" if", "[\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def", "side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs: rest", "Name of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse result that is", "Have the API include the hashes of rows values. Defaults to: False. **kwargs:", "to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO: Add wait till", "to: 300. operator (:obj:`str`, optional): Defines how the last_registered attribute of each client", "actions using the Tanium API.\"\"\" from __future__ import absolute_import from __future__ import division", "raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for this question. Returns: :obj:`dict`", "{info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\", ] m = \", \".join(m)", "if page_size: paging_get_args = {k: v for k, v in get_args.items()} while True:", "export_id is not XML format or return_dict and return_obj False, return the raw", "ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] =", "return None def map_select_params(self, pq): \"\"\"Map parameters to sensors on the left hand", "lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "\"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\" data = result.str_to_obj(text=data, src=src, try_int=False)", "call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this many", "trailing (:obj:`str`, optional): Append this text to each line. Defaults to: \"\". **kwargs:", "\"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k", ") self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end - start m =", "lvl=lvl) self.obj = obj self.adapter = adapter self._result = result self._last_result = result", "self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get", "on the left hand side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values =", "adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if filters is not None: get_args[\"cache_filters\"]", "True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None):", "False), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property", "cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all", "pq.parameter_values selects = pq.question.selects or [] for select in selects: if not param_values:", "= 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True", "self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] =", "m = \"Now mapping parameters for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m)", "object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\",", "id returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`:", "all_values_flag (:obj:`bool`, optional): Have filter match all values instead of any value. Defaults", "= m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a", "to: 2. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of", "kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList()", "class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format", "index: {idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list =", "client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args)", "= \"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod", "value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`:", "\"\". derive_default (:obj:`bool`, optional): Get default value from parameter definition if value is", "initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m =", "= \"Reached max page count {c}, considering all clients fetched\" m = m.format(c=max_page_count)", "p.value return ret @property def params(self): \"\"\"Get the parameters that are set for", "cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m", "(:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to:", "for CSV format and get an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV", "= 2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result", "Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls,", "\"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator", "indices in str form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r}, params: {params},", "Adapter to use for this workflow. id (:obj:`int`): id of question to fetch.", "answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this questions server side export. Args:", "of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\",", "\"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash =", "workflow. id (:obj:`int`): id of question to fetch. lvl (:obj:`str`, optional): Logging level.", "invalid, must be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def", "True. use_first (:obj:`bool`, optional): If index is None and there is no exact", "None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter", "= self.params_defined.get(key, None) if param_def is None: m = \"Parameter key {o!r} is", "on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N number of clients at", "[\"\", None]: derived_default = pval elif pvals: derived_default = pvals[0] else: derived_default =", "set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self,", "self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value == \"\": value = param_def.get(\"derived_default\",", "select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash", "key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get", "a filter for this sensor to be used in a question. Args: value", "to: 5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and", "values Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`:", "return_dict (:obj:`bool`, optional): If export_id is an XML format, return a dictionary object.", "Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of", "seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g.", "m = \"Server Side Export completed: {status}\" m = m.format(status=status) self.log.info(m) break if", "m = [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m =", "self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def ask(self, **kwargs):", "this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional):", "return OrderedDict((p[\"key\"], p) for p in params) @property def param_values(self): \"\"\"Get all of", ":meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args =", "\"\"\"Map parameters to sensors on the left hand side of the question.\"\"\" param_cls", "the right hand side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors", "values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping", "\"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self):", "this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret =", "\"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef not in", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt = start +", "False if headers else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "if x.question.from_canonical_text: return x return None def map_select_params(self, pq): \"\"\"Map parameters to sensors", "all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select =", "set. Throws exception if False and key not in :attr:`Sensor.param_keys`. Defaults to: True.", "of parameter to set. value (:obj:`str`, optional): Value of parameter to set. Defaults", "Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod", "is False!\", ] err = \", \".join(err) err = [err, \"Supply an index", "have API sort the return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get", "= \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects, parameter", "group_sensors: m = \"No question group sensors defined, not mapping group params\" self.log.debug(m)", "attr, None)) for attr in attrs] bits += [atmpl(k=k, v=v) for k, v", ".. import utils from .. import results class Workflow(object): def __init__(self, adapter, obj,", "= self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result )", "SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS", "use_first is False!\", ] err = \", \".join(err) err = [err, \"Supply an", "Defaults to: 600. sleep (:obj:`int`, optional): Wait N seconds between fetching each page.", "poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients for this question.", "\".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0,", "m = \"Type {o!r} is invalid, must be one of {vo}\" m =", "many seconds before expiring the cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait", "be used in a question. Args: value (:obj:`str`): Filter sensor rows returned on", "self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt}, considering all", "in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional):", "API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If not 0, only poll N", "start m = [ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients:", "\"\"\"Build a set of filters to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "{o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m = \"Reached", "m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs", "workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object", "return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If", "result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated from. Defaults to: None.", "= \"New polling loop #{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if", "page_data.rows m = \"Received page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or", "If index is None and one of the parse results is an exact", "if max_poll_count and poll_count >= max_poll_count: m = \"Reached max poll count {c},", "self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ):", "parameter values left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0)", "dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional): If export_id is XML format,", "or 23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\":", "\"\". Defaults to: True. delim (:obj:`str`, optional): String to put before and after", "clients total is N percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If not", "that are not in the parameters definition for this sensor to be set.", "= result self._last_result = result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\"", "m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas return datas def", "an export_id. Args: hashes (:obj:`bool`, optional): Have the API include the hashes of", "\"has exact match: {em}\".format(em=True if self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits))", "response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"])", "max_age_seconds (:obj:`int`, optional): How old a sensor result can be before we consider", ":data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is invalid,", "no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start =", "this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self, \"_params\"): self._params", "lvl=\"info\"): \"\"\"Get a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "defined, and no value is set, try to derive the default value from", "all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args)", "or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level,", "ask it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if", "m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for groups, parameter values", "any paging, which means ALL answers will be returned in one API response.", "result=result) def _check_id(self): \"\"\"Check that question has been asked by seeing if self.obj.id", "pvals: derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"],", "= [\"Started Server Side for CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m", "= 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while", "result end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting", "until N seconds for pct of clients total instead of until question expiration.", "2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5,", "m.format(c=total_rows) log.info(m) break page_count += 1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result", "\"\"\"Get the key value pairs of the filter for this sensor. Returns: :obj:`list`", "this workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API", "has been asked by seeing if self.obj.id is set.\"\"\" if not self.obj.id: m", "total instead of until question expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If", "elapsed = end - start m = [ \"Finished polling in: {dt}\", \"clients", "possible (single line in each cell) Defaults to: False. headers (:obj:`bool`, optional): Include", "p.get(\"values\", []) if pdef not in [\"\", None]: derived_default = pdef elif pval", "param_values: m = \"No more parameter values left to map\" self.log.debug(m) return key", "by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name (:obj:`str`):", "this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow()", ">= max_row_count: m = \"Hit max pages of {max_row_count}, considering all answers received\"", "between fetching each page. Defaults to: 5. **kwargs: rest of kwargs: Passed to", "m = \"No more parameter values left to map\" self.log.debug(m) return key =", "(:obj:`int`, optional): When page_size is not 0, have the API keep the cache", "1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received", "to it. If this is None, a new CacheFilterList will be created with", "name of parameter to set. value (:obj:`str`, optional): Value of parameter to set.", "\"\". trailing (:obj:`str`, optional): Append this text to each line. Defaults to: \"\".", "supplied, the last_registration filter generated by this method will be appended to it.", "it in \"derived_default\" key for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs", "An export id returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`.", "performing actions using the Tanium API.\"\"\" from __future__ import absolute_import from __future__ import", "this questions server side export. Args: export_id (:obj:`str`): An export id returned from", "cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse result", "= self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not group: m =", "__str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format", "infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for", "will be appended to it. If this is None, a new CacheFilterList will", "adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self):", "vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set", "to use for this workflow. last_reg (:obj:`int`, optional): Only return clients that have", "export for completion. Args: export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or", "@classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by name. Args:", "\", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m", "enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return", "to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result)", "- now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj)", "= self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] =", "ret[k] = \"\" for p in self.params: ret[p.key] = p.value return ret @property", "(:obj:`bool`, optional): Get default value from parameter definition if value is \"\". Defaults", "{pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m = \"Picking", "to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"]", "d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id", "object that ``obj`` was generated from. Defaults to: None. \"\"\" self._lvl = lvl", "disables paging and gets all clients in one call. Defaults to: 1000. max_page_count", "for this question one page at a time. Args: page_size (:obj:`int`, optional): Size", ":meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults", "= end - start m = \"Finished polling for Server Side Export in", "exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m", "else: derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p in", "kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO: Add", "rows values Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns:", "else: err = [ \"No index supplied\", \"no exact matching parsed result\", \"and", "\"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\":", "format using server side export. Args: export_id (:obj:`str`): An export id returned from", "datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt}, considering all answers in\" m", "end = datetime.datetime.utcnow() elapsed = end - start m = [ \"Finished polling", "and after parameter key name when sending to API. Defaults to: \"||\". allow_undefined", "== \"failed\": m = \"Server Side Export failed: {status}\" m = m.format(status=status) raise", "\"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or", "300. operator (:obj:`str`, optional): Defines how the last_registered attribute of each client status", "new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl", "filters is not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"]", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name))", ") if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs):", "\".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start", "start response for CEF format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code)", "\"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls =", "response for XML format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m)", "{c}\", ] m = \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return", "time from the API. If 0, disables paging and gets all clients in", "= trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side", "derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p in params)", "to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have the API return all rows", "param_def is None: m = \"Parameter key {o!r} is not one of the", "Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj = True returns ResultSetList ApiModel", "parse results returned for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical =", "If not 0, wait until N seconds for pct of clients total instead", "Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits", "select.WORKFLOW = self return select class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns:", "= [x for x in group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition:", "only poll N times. Defaults to: 0. **kwargs: rest of kwargs: Passed to", "store it in \"derived_default\" key for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\"", "{pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow()", "\"\"\"Get parse results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "[]: if not param_values: m = \"No more parameter values left to map\"", "{pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical", "page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m)", "count: {c}\", ] m = \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m)", "(:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if", "build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of filters to", "to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args", "raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end -", "{k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group):", "group: m = \"Empty group, not mapping group params\" self.log.debug(m) return if not", "the cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait N seconds between fetching", "log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\":", ":obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\",", "[\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m", "**kwargs) self._last_result = result self.obj = result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True,", "the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not", "= [\"Received Server Side Export start response for XML format\", \"code={c}\"] m =", "filtering on value. Defaults to: True. not_flag (:obj:`bool`, optional): If set, negate the", "use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and ask it. Args: index (:obj:`int`,", "self.get_canonical: pq = self.get_canonical m = \"Picking parsed question based on exact match:", "= result infos = result() self._last_infos = infos m = \"Received answers info:", "Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl)", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that", "to derive the default value from each parameters definition. Defaults to: True. allow_empty_params", "of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format or", "fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result", "not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count", "\"\", or None, throw an exception. Defaults to: True. \"\"\" select = sensor.build_select(", "page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows +=", "value is \"\". Defaults to: True. delim (:obj:`str`, optional): String to put before", "\"New polling loop #{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct", "if that happens page_datas = page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows", ":obj:`str`: If return_obj = True returns ResultSetList ApiModel object. If return_dict = True", "set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value in [\"\", None] and", "yield obj if page_size: paging_get_args = {k: v for k, v in get_args.items()}", "cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas", "get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows", "hand side of the question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`,", "(:obj:`bool`, optional): Include column headers. Defaults to: True. hashes (:obj:`bool`, optional): Have the", "\"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\":", "for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info", "pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt}, considering", "return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question", "\"Received expected row_count {c}, considering all answers received\" m = m.format(c=data.row_count) self.log.info(m) break", "hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" # (numeric", "allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined, and the value is not", "self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter self._result = result", "= [] for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values", "to map\" self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition: m = \"No", "is set.\"\"\" if not self.obj.id: m = \"No id issued yet, ask the", "page count {c}, considering all clients fetched\" m = m.format(c=max_page_count) log.info(m) break if", "map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m =", "self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod", "is N percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If not 0, wait", "datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m", "m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or []) >= max_row_count:", ">= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt", "optional): If export_id is XML format, return a ResultSet object. Defaults to: True.", "Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has", "group=pq.question.group) m = \"Finished mapping parameters for groups, parameter values left: {pv!r}\" m", "cache=result_cache) log.info(m) for obj in result_obj: yield obj if page_size: paging_get_args = {k:", "Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj,", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use", "(:obj:`bool`, optional): If index is None and one of the parse results is", "to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\"", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked (id is", "export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for XML format\", \"export_id={e!r}\"] m", "\"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter( self,", "self.obj = result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a", "(numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\":", "optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return", "a parse result and ask it. Args: index (:obj:`int`, optional): Index of parse", "rows values. Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes:", "cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing:", ">= max_poll_count: m = [ \"Server Side Export completed\", \"reached max poll count", "cache of clients for this many seconds before expiring the cache. Defaults to:", "Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked (id is set),", "self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects, parameter values left: {pv!r}\" m", "result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF format\", \"export_id={e!r}\"] m = \",", "x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id", "Index of parse result to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If", "\"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k))", "type=None, ): \"\"\"Set a filter for this sensor to be used in a", "= self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter for this sensor.", "this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList", "v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to filters on the", "\"derived_default\" key for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition", "till error_count / no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", "else: raise exceptions.ModuleError(m) elif derive_default and value == \"\": value = param_def.get(\"derived_default\", \"\")", "# -*- coding: utf-8 -*- \"\"\"Workflow encapsulation package for performing actions using the", "True. delim (:obj:`str`, optional): String to put before and after parameter key name", "\"\"\"Get the answers for this question. Args: hashes (:obj:`bool`, optional): Have the API", "sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count", "\"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects, parameter values", "be created with the last_registration filter being the only item in it. Defaults", "CacheFilterList will be created with the last_registration filter being the only item in", "set, try to derive the default value from each parameters definition. Defaults to:", "for pct of clients total instead of until question expiration. Defaults to: 0.", "ALL answers will be returned in one API response. For large data sets", "self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the", "m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size", "m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server", "= {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r", "params: if not param_values: m = \"No more parameter values left to map\"", "of clients at a time from the API. If 0, disables paging and", "exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else:", "Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] =", "to: False. headers (:obj:`bool`, optional): Include column headers. Defaults to: True. hashes (:obj:`bool`,", ":obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return", "self.params: if param.value in [\"\", None] and not allow_empty_params: m = \"Parameter {p.key!r}", "= self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values: m", "= 1 m = \"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache)", "optional): Value of parameter to set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get", "set, negate the match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How old a", "= page_data.rows m = \"Received page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows", "optional): If not 0, wait until N clients have total instead of ``estimated_total``", "= [ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total:", "\"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs)", ":meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object to", "optional): Append this text to each line. Defaults to: \"\". **kwargs: rest of", "= \"Picking parsed question based on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m)", "start = datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj", "\"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter,", "10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator", "= datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"]", "2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result =", "Defaults to: 2. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest", "this workflow. text (:obj:`str`): Question text to parse. lvl (:obj:`str`, optional): Logging level.", "If not 0, wait until N clients have total instead of ``estimated_total`` of", "lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start =", "in {now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count:", "Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl,", "\"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt", "= \" index: {idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format", "When page_size is not 0, have the API keep the cache of clients", "If True have the API return all rows that do not match the", "self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished polling", "self._last_result = result datas = result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"]", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs: rest of kwargs: Passed to", "= row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj =", "self._last_result = result end = datetime.datetime.utcnow() elapsed = end - start m =", "result datas = result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id", "= filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration", "param_values(self): \"\"\"Get all of the parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret", "cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count += 1 m = \"New", "= result self.obj = result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ):", "= result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added", "parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls,", "= \"Finished getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed)", "absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals", "page_size: paging_get_args = {k: v for k, v in get_args.items()} while True: if", "Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def", "0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3,", "= utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args)", "\"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\",", "\"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1", "lvl=\"info\", **kwargs): \"\"\"Get parse results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have the API", "only item in it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator)", "API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return", "API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result =", "Defaults to: True. use_first (:obj:`bool`, optional): If index is None and there is", "status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get", "text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in", "use the max age property of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`,", "cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] =", "expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If not 0, wait until N", "is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex:", "Defaults to: True. delim (:obj:`str`, optional): String to put before and after parameter", "elapsed = end - start m = \"Finished getting answers in {dt}\" m", "key and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in self.params_defined:", "Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td", "start m = \"Finished getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas", "bits=bits) @property def get_canonical(self): \"\"\"Return any parse result that is an exact match.\"\"\"", "result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by id.", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls,", "None]: derived_default = pval elif pvals: derived_default = pvals[0] else: derived_default = \"\"", "= r.text if \"xml\" in export_id and (return_dict or return_obj): result = results.Soap(", "\"\"\"Start up a server side export for XML format and get an export_id.", "ClientStatus object to have API sort the return on. Defaults to: \"last_registration\". page_size", "def _check_id(self): \"\"\"Check that question has been asked by seeing if self.obj.id is", "err = \", \".join(err) err = [err, \"Supply an index of a parsed", "max poll count {c}\", \"status {status}\", ] m = \", \".join(m) m =", "a set of filters to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for key in", "kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format or return_dict", "cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield obj if", "map\" self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition: m = \"No parameters", "return select class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id of question to", "question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "means ALL answers will be returned in one API response. For large data", "@classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs", "bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits +=", "the question. Args: lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest", "start m = \"Finished getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows or", "rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format", "stop_dt: m = \"Reached stop_dt {stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt)", "self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition: m = \"No parameters defined", "exact matching parsed result\", \"and use_first is False!\", ] err = \", \".join(err)", "self.obj[index] m = \"Picking parsed question based on index {index}: {pq.question}\" m =", "not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\",", "length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield obj", "cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server", "= p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef", "1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj =", "Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question", "object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits =", "key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for this sensor.", "cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received initial answers: {d.rows}\",", "[])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed", "= adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has", "an exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return x return None", "= ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters =", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text (:obj:`str`): Question text", "p) for p in params) @property def param_values(self): \"\"\"Get all of the parameter", "to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "parameter definitions for this sensor. Notes: Will try to resolve a default value", "from parameter definition if value is \"\". Defaults to: True. delim (:obj:`str`, optional):", "all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end", "for completion. Args: export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv`", "that do not match the operator. Defaults to: 1000. filters (:obj:`object`, optional): If", "this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end - start", "any([x.question.from_canonical_text for x in result_obj]) m = \"Received {n} parse results (any exact", "each client status is compared against the value in last_reg. Must be one", "sensor result can be before we consider it invalid. 0 means to use", "m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id", "[\"Started Server Side for CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m =", "export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional):", "in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None) if param_def is", "= self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos = infos m =", "workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text", "optional): Attribute of a ClientStatus object to have API sort the return on.", "of parse result to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If index", "cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server", "SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3 months,", "end - start m = [ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\",", "page returns no answers or the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`:", "question expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If not 0, wait until", "end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished polling for", "key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None) if", "result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache,", "11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\"", "not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value", "src=src, try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return", "now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex =", "k, v in get_args.items()} while True: if max_page_count and page_count >= max_page_count: m", "to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has", "Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter,", "True: if max_page_count and page_count >= max_page_count: m = \"Reached max page count", "self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this questions", "\"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs", "this method will be appended to it. If this is None, a new", "rows count {c}, considering all clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count", "**kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\"", "= op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag =", "the return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N number of", "Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args)", "Attribute of a ClientStatus object to have API sort the return on. Defaults", "Object to use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to:", "derive_default and value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key)", "1 m = \"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m)", "**kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\"", "if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m =", "self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash =", "\"Reached total rows count {c}, considering all clients fetched\" m = m.format(c=total_rows) log.info(m)", "datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status =", "\"xml\" in export_id and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body,", "API sort the return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N", "object. Defaults to: False. return_obj (:obj:`bool`, optional): If export_id is XML format, return", "polling for Server Side Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m)", "for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get", "to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs)", "optional): Wait until the percentage of clients total is N percent. Defaults to:", "in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self,", "\"failed\": m = \"Server Side Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m)", "value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\" m", "the parse result indices in str form.\"\"\" pq_tmpl = \" index: {idx}, result:", "Defaults to: 300. operator (:obj:`str`, optional): Defines how the last_registered attribute of each", "result data as None sometimes # need to refetch data for N retries", "\"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"},", "\"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits =", "info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end -", "of rows values. Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`.", "[] for select in selects: if not param_values: m = \"No more parameter", "{status}\", ] m = \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if", "with the last_registration filter being the only item in it. Defaults to: None.", "to: \"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args", "{s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in", "= result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor", "returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an XML format, return", "= m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m = \"Reached {now_pct} out", "log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m = [", "from each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor has", "returns no answers or the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList", "= \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor", "params_defined(self): \"\"\"Get the parameter definitions for this sensor. Notes: Will try to resolve", "self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property", "parsed question based on index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif", "**kwargs): \"\"\"Get the answers for this question. Args: hashes (:obj:`bool`, optional): Have the", "return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a", "= self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished", "return filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2,", "value from parameter definition if value is \"\". Defaults to: True. delim (:obj:`str`,", "m.format(pq=pq) self.log.info(m) else: err = [ \"No index supplied\", \"no exact matching parsed", "and return_obj False, return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict`", "ApiModel object. If return_dict = True returns dict. Otherwise, return str. \"\"\" self._check_id()", "\"export_id: {e!r}\"] m = \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data =", "type as this. Must be one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict", "= \"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key,", "\".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create", "Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO: Add wait", "all_rows = data.rows page_count = 1 page_rows = all_rows while True: if len(all_rows", "self.log.debug(m) return for group_filter in group.filters or []: if not param_values: m =", "where API returns result data as None sometimes # need to refetch data", "Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0", "sensor to the left hand side of the question. Args: sensor (:obj:`Sensor`): Sensor", "for XML format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return", "\"\"\"Start up a server side export for CEF format and get an export_id.", "datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td,", "param.value in [\"\", None] and not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r}", "no answers or the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API", "self.log.info(m) break if max_poll_count and poll_count >= max_poll_count: m = \"Reached max poll", "} if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] =", "answers from clients for this question. Args: poll_sleep (:obj:`int`, optional): Check for answers", "params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values: m = \"No", "return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of", "m = \"Operator {o!r} is invalid, must be one of {vo}\" m =", "the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or []", "the hashes of rows values. Defaults to: False. **kwargs: rest of kwargs: Passed", "p in params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals =", "value is set, try to derive the default value from each parameters definition.", "a page with no answers, considering all answers received\" self.log.info(m) break if max_page_count", "datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting {rows} answers in", "9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator):", "all answers received\" self.log.info(m) break if max_page_count and page_count >= max_page_count: m =", "self.log.info(m) datas = result() self._last_datas = datas return datas def answers_get_data_paged( self, page_size=1000,", "parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq,", "sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object to have API sort the", "an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters (:obj:`object`,", "if not group: m = \"Empty group, not mapping group params\" self.log.debug(m) return", "0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if", "export_id (:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs: rest of kwargs: Passed", "from. Defaults to: None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj", "optional): Get default value from parameter definition if value is \"\". Defaults to:", "of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start", "filter_vals(self): \"\"\"Get the key value pairs of the filter for this sensor. Returns:", "= \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if", "sensor = select.sensor if not sensor.parameter_definition: m = \"No parameters defined on sensor", "used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg", "= m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m = \"Server Side Export", "= param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\" m =", "all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >=", "CSV format and get an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows", "self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total = est_total if poll_total and", "this many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the API keep", "object to have API sort the return on. Defaults to: \"last_registration\". page_size (:obj:`int`,", "1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch errors where", "= self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result =", "a CacheFilterList object is supplied, the last_registration filter generated by this method will", "= \"No more parameter values left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"])", "getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1 m = \"Received initial", "Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"):", "text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True,", "max_poll_count (:obj:`int`, optional): If not 0, only poll N times. Defaults to: 0.", "end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting answers", "match all values instead of any value. Defaults to: False. type (:obj:`str`, optional):", "# SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, #", "Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in self.params_defined: ret[k] = \"\"", "Size of each page to fetch at a time. Defaults to: 1000. max_page_count", "self._last_result = result self.obj = result() def ask(self, **kwargs): \"\"\"Ask the question. Args:", "= m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield obj if page_size: paging_get_args", "one of the parse results is an exact match, pick and ask it.", "\"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result", "page_datas page_data = page_datas[0] page_rows = page_data.rows m = \"Received page #{c} answers:", "return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl", "in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m =", "\"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\":", "if pdef not in [\"\", None]: derived_default = pdef elif pval not in", "m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj]) m = \"Received", "m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if", "If set, negate the match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How old", "is compared against the value in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults", "loop for answers until for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m)", "export_id, **kwargs): \"\"\"Get the status for this questions server side export. Args: export_id", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\"", "last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If", "until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0]", "Args: value (:obj:`str`): Filter sensor rows returned on this value. operator (:obj:`str`, optional):", "m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield", "= m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ):", "path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m)", "import datetime import json import time from collections import OrderedDict from . import", "is not one of the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if", "\"Type {o!r} is invalid, must be one of {vo}\" m = m.format(o=type, vo=list(TYPE_MAP.keys()))", "getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count =", "to be set. Throws exception if False and key not in :attr:`Sensor.param_keys`. Defaults", "\"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already", "Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ]", "value pairs of the filter for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\"", "self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined: if key", "= ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None", "\"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m = \", \".join(m) m = m.format(", "\"\"\"Get all of the parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret =", "900. hashes (:obj:`bool`, optional): Have the API include the hashes of rows values", "import exceptions from .. import utils from .. import results class Workflow(object): def", "if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt", "not 0, wait until N seconds for pct of clients total instead of", "sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in self.params_defined: ret[k]", "+= row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows", "m = \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count =", "to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result)", "(:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits", "to: True. use_first (:obj:`bool`, optional): If index is None and there is no", "paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\",", "= \"No parameters defined on sensor {s}, going to next\" m = m.format(s=sensor)", "= m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow()", "Export completed\", \"reached max poll count {c}\", \"status {status}\", ] m = \",", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object", "idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text),", "m = m.format(c=total_rows) log.info(m) break page_count += 1 row_start += row_count paging_get_args[\"row_start\"] =", "start response for XML format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code)", "Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {}", "None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"]", "to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\"", "allow_empty_params=False ): \"\"\"Add a sensor to the left hand side of the question.", "from API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If not 0, only poll", "else False), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits)", "to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id))", ">= data.row_count: m = \"Received expected row_count {c}, considering all answers received\" m", "one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type)", "each line. Defaults to: \"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns:", "return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse result that is an", "to: 600. sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults", "now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return ret def refetch(self):", "if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result =", "result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos = infos m", "pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\", []) if", "of clients total is N percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If", "poll count {c}, considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos", "m = \"Reached max page count {c}, considering all answers in\" m =", ") data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\" data =", "to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML format or return_dict and return_obj", "= pq.parameter_values if not group: m = \"Empty group, not mapping group params\"", "group params\" self.log.debug(m) return for group_filter in group.filters or []: if not param_values:", "use_exact_match and self.get_canonical: pq = self.get_canonical m = \"Picking parsed question based on", "in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or []) >=", "all clients fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m", "= ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result", "result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side Export start", "result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size", "definition if value is \"\". Defaults to: True. delim (:obj:`str`, optional): String to", "operator (:obj:`str`, optional): Operator to use for filter_value. Must be one of :data:`OPERATOR_MAP`.", "Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value)", "get all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size is not", "\"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in", "sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select)", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "\"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m = \",", "v in get_args.items()} while True: if max_page_count and page_count >= max_page_count: m =", "bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by name.", "type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag =", "use_first (:obj:`bool`, optional): If index is None and there is no exact match,", "@property def filter(self): \"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API", "exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for this question. Returns: :obj:`dict` \"\"\"", "or []) >= max_row_count: m = \"Hit max pages of {max_row_count}, considering all", "Defaults to: False. sleep (:obj:`int`, optional): Wait N seconds between fetching each page.", "time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end - start m = [ \"Finished", "info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99,", "(:obj:`str`, optional): Operator to use for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults", "Defaults to: False. headers (:obj:`bool`, optional): Include column headers. Defaults to: True. hashes", "(:obj:`int`): id of question to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to:", "+= 1 if max_poll_count and poll_count >= max_poll_count: m = [ \"Server Side", "Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl,", "pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self,", "to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id()", "return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl", "\"Reached stop_dt {stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if", "side export for XML format and get an export_id. Args: hashes (:obj:`bool`, optional):", "in a question. Args: value (:obj:`str`): Filter sensor rows returned on this value.", "poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count += 1", "get_canonical(self): \"\"\"Return any parse result that is an exact match.\"\"\" for x in", "<= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while", "\"Reached max poll count {c}, considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m)", "\".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\",", "m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = {", "{\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\":", "ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr,", "parse result to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If index is", "if headers else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result", "for this questions server side export. Args: export_id (:obj:`str`): An export id returned", "\"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\":", "= [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs]", "rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs)", "\"No more parameter values left to map\" self.log.debug(m) return sensor = select.sensor if", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl (:obj:`str`, optional): Logging level.", "based on index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and", "m = m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m = \"Reached total", "do not match the operator. Defaults to: 1000. filters (:obj:`object`, optional): If a", "\"Reached {now_pct} out of {pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct))", "id issued yet, ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration", "any value. Defaults to: False. type (:obj:`str`, optional): Have filter consider the value", "Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined, and no", "and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code,", "server side export for CSV format and get an export_id. Args: flatten (:obj:`bool`,", "None and there is no exact match, pick the first parse result and", "\".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0, #", "True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result", "obj self.adapter = adapter self._result = result self._last_result = result def __repr__(self): \"\"\"Show", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt", "m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering", "hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for this question one page at", "parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor", "{exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for idx, pq in enumerate(self.obj): pq_txt", "use_exact_match (:obj:`bool`, optional): If index is None and one of the parse results", "be one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if type:", "end - start m = \"Finished getting answers in {dt}\" m = m.format(dt=elapsed)", "class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format", "= [] return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0,", "unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args =", "\", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep)", "the API include the hashes of rows values Defaults to: False. sleep (:obj:`int`,", "Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None) if param_def is None: m", "= [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m =", ":meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] =", "question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj = result() def ask(self,", "m = \"No more parameter values left to map\" self.log.debug(m) return sensor =", "has parameters defined, and no value is set, try to derive the default", "= \", \".join(err) err = [err, \"Supply an index of a parsed result:\",", "): \"\"\"Set a parameters value for this sensor. Args: key (:obj:`str`): Key name", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id of sensor", "m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id,", "bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def", "= m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for x in group_sensors", "between fetching each page. Defaults to: 2. lvl (:obj:`str`, optional): Logging level. Defaults", "import OrderedDict from . import exceptions from .. import utils from .. import", "This will not use any paging, which means ALL answers will be returned", "clients fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m =", "use for this workflow. last_reg (:obj:`int`, optional): Only return clients that have registered", "return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this questions server", "to filters on the right hand side of the question.\"\"\" param_cls = self.api_objects.Parameter", "ParameterList API object \"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params", "self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value in [\"\", None] and not", "poll N times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`.", "exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a", "= [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits += [", "it invalid. 0 means to use the max age property of the sensor.", "= \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False,", "exception if False and key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def", "# (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or 23K or", "data = self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object", "op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag", "to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging, which means ALL answers", "self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes", "cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result()", "8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format", "json import time from collections import OrderedDict from . import exceptions from ..", "True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined, and the value is", "\", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs):", "Adapter to use for this workflow. last_reg (:obj:`int`, optional): Only return clients that", "\"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on value. Defaults to: True.", "this text to each line. Defaults to: \"\". **kwargs: rest of kwargs: Passed", "self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] =", "\"No question group sensors defined, not mapping group params\" self.log.debug(m) return for group_filter", "\"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in", "# TODO: Add wait till error_count / no_results_count == 0 self._check_id() cmd_args =", "for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor =", "get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m =", "raise exceptions.ModuleError(m) elif derive_default and value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim", "status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end - start m =", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked", "for performing actions using the Tanium API.\"\"\" from __future__ import absolute_import from __future__", "response for CSV format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m)", "at a time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to", "**kwargs ): \"\"\"Poll for answers from clients for this question. Args: poll_sleep (:obj:`int`,", ":obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs)", "going to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id =", "of the parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict() for", "Defaults to: \"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\"", "[\"Started Server Side for XML format\", \"export_id={e!r}\"] m = \", \".join(m) m =", "self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False):", "sensor rows returned on this value. operator (:obj:`str`, optional): Operator to use for", "to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API", "\"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m = \"Type", "parameter definition if value is \"\". Defaults to: True. delim (:obj:`str`, optional): String", "headers. Defaults to: True. hashes (:obj:`bool`, optional): Have the API include the hashes", "\"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"]", "= adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any", "= self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question. Args:", "= \"No more parameter values left to map\" self.log.debug(m) return sensor = select.sensor", "return ret @property def params(self): \"\"\"Get the parameters that are set for this", "pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p", "be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "to use for this workflow. id (:obj:`int`): id of question to fetch. lvl", "\"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt", "poll count {c}\", \"status {status}\", ] m = \", \".join(m) m = m.format(c=max_poll_count,", "datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting answers in {dt}\"", "data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data", "= paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m = [ \"Received page_rows={page_rows}\",", "end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting {rows}", "m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical m", "to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked (id is set), we", "parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err = [ \"No index", "True returns ResultSetList ApiModel object. If return_dict = True returns dict. Otherwise, return", "if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\",", "select.sensor = self.api_objects.Sensor() for key in self.params_defined: if key not in self.param_values and", "Defaults to: 5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count", "] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys] else: vals", "= m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value", "in self.params_defined: ret[k] = \"\" for p in self.params: ret[p.key] = p.value return", "more parameter values left to map\" self.log.debug(m) return sensor = select.sensor if not", "k)) for k in keys] else: vals = [] return vals def set_filter(", "def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export for completion.", "to: None. use_exact_match (:obj:`bool`, optional): If index is None and one of the", "**kwargs ): \"\"\"Start up a server side export for CSV format and get", "to: 900. hashes (:obj:`bool`, optional): Have the API include the hashes of rows", "against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is", "= m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt", "N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until the percentage of", "\"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def", "param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def", "pval elif pvals: derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default", "self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select()", "happens page_datas = page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows = page_data.rows", "TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is invalid, must be one of", "self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos = infos m = \"Received", "Have the API include the hashes of rows values Defaults to: False. **kwargs:", "as this. Must be one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict =", "= \"No parse results returned for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m)", "{\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\":", "question. Args: lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of", "coding: utf-8 -*- \"\"\"Workflow encapsulation package for performing actions using the Tanium API.\"\"\"", "= True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"]", "pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end", "**kwargs): \"\"\"Poll a server side export for completion. Args: export_id (:obj:`str`): An export", "= pq_tmpl.format pq_list = [] for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl(", "first parse result and ask it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`.", "Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\"", "elif pval not in [\"\", None]: derived_default = pval elif pvals: derived_default =", "if poll_total and poll_total <= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total)", "lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj =", "seconds before expiring the cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait N", "Result object that ``obj`` was generated from. Defaults to: None. \"\"\" self._lvl =", "= pval elif pvals: derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"] =", "operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for this sensor", "of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m = \", \".join(m) m", "Export start response for CSV format\", \"code={c}\"] m = \", \".join(m) m =", "m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m = \"Server", "and no value is set, try to derive the default value from each", "self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW =", "seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have the API include the hashes", "Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was", ":meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg (:obj:`int`, optional):", "clients in one call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up", "instead of any value. Defaults to: False. type (:obj:`str`, optional): Have filter consider", "to: True. not_flag (:obj:`bool`, optional): If set, negate the match. Defaults to: False.", "the first parse result and ask it. **kwargs: rest of kwargs: Passed to", "values instead of any value. Defaults to: False. type (:obj:`str`, optional): Have filter", "seeing if self.obj.id is set.\"\"\" if not self.obj.id: m = \"No id issued", "fetch pages until a page returns no answers or the expected row count", "Server Side for CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id)", "] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def", "Notes: This will not use any paging, which means ALL answers will be", "self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"]", "[\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys] else: vals = [] return", "index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq", "= all_rows while True: if len(all_rows or []) >= data.row_count: m = \"Received", "line. Defaults to: \"\". trailing (:obj:`str`, optional): Append this text to each line.", "one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type", "derive_default (:obj:`bool`, optional): Get default value from parameter definition if value is \"\".", "api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\"", "error_count / no_results_count == 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj", "considering all clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count += 1 row_start", "\"\"\"Poll for answers from clients for this question. Args: poll_sleep (:obj:`int`, optional): Check", "self.log.debug(m) return if not group_sensors: m = \"No question group sensors defined, not", "page_size (:obj:`int`, optional): Size of each page to fetch at a time. Defaults", "Defaults to: 900. hashes (:obj:`bool`, optional): Have the API include the hashes of", "the question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor", "optional): Get N number of clients at a time from the API. If", "get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] =", "Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList()", "N number of clients at a time from the API. If 0, disables", "wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs", "of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"]", "returned for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for", "optional): Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index]", "result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question", "hashes (:obj:`bool`, optional): Have the API include the hashes of rows values. Defaults", "0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start", "= utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus()", "match the operator. Defaults to: 1000. filters (:obj:`object`, optional): If a CacheFilterList object", "to: 0. max_poll_count (:obj:`int`, optional): If not 0, only poll N times. Defaults", "more parameter values left to map\" self.log.debug(m) return m = \"Now mapping parameters", "for this workflow. id (:obj:`int`): id of sensor to fetch. lvl (:obj:`str`, optional):", "client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code:", "right hand side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values", "None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object to have API sort", "= self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total = est_total if poll_total", "v=v) for k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls =", "\"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())),", "\"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex", "self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients", "= [\"Received Server Side Export start response for CEF format\", \"code={c}\"] m =", "new CacheFilterList will be created with the last_registration filter being the only item", "the left hand side of the question. Args: sensor (:obj:`Sensor`): Sensor workflow object.", "m = [\"Received Server Side Export start response for CSV format\", \"code={c}\"] m", "m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get", "\"greaterequal\". not_flag (:obj:`int`, optional): If True have the API return all rows that", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg (:obj:`int`, optional): Only return", "v for k, v in get_args.items()} while True: if max_page_count and page_count >=", "in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info.", "\"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for p in", "getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo", "[ \"Server Side Export completed\", \"reached max poll count {c}\", \"status {status}\", ]", "sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse", "{} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj", "{pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m =", "} PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in", "now_td = datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\":", "m = \"Reached {now_pct} out of {pct}, considering all answers in\" m =", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to", "have the API return all rows that do not match the operator. Defaults", "Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def", "result self._last_result = result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return", "answers every N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until the", "max_row_count and len(all_rows or []) >= max_row_count: m = \"Hit max pages of", "if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m = [", "{dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False,", "Include column headers. Defaults to: True. hashes (:obj:`bool`, optional): Have the API include", "param_values = pq.parameter_values if not group: m = \"Empty group, not mapping group", "self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs", "completion. Args: export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or", "return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and", "exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type]", "start m = \"Finished polling for Server Side Export in {dt}, {status}\" m", "optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return", "import print_function from __future__ import unicode_literals import datetime import json import time from", "from __future__ import unicode_literals import datetime import json import time from collections import", "\"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property", "sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self, \"_params\"): self._params =", "is an exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return x return", "\"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate", "for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []),", "of each page to fetch at a time. Defaults to: 1000. max_page_count (:obj:`int`,", "True cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers", "for k in self.params_defined: ret[k] = \"\" for p in self.params: ret[p.key] =", "optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute", "\"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\", ] m =", "in each cell) Defaults to: False. headers (:obj:`bool`, optional): Include column headers. Defaults", "level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(),", "using the Tanium API.\"\"\" from __future__ import absolute_import from __future__ import division from", "to use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "\"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits", "is created on initial get answers page alive for N seconds. Defaults to:", "= select.sensor if not sensor.parameter_definition: m = \"No parameters defined on sensor {s},", "result to ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If index is None", "{t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj])", "\"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\":", "clients that have registered in N number of seconds. Defaults to: 300. operator", "not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the", "Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end", "= result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property", "include the hashes of rows values. Defaults to: False. **kwargs: rest of kwargs:", "__future__ import print_function from __future__ import unicode_literals import datetime import json import time", "all rows that do not match the operator. Defaults to: 1000. filters (:obj:`object`,", "= now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"],", "API include the hashes of rows values. Defaults to: False. **kwargs: rest of", "= True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side Export start response for", "\"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects", "and value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param", "= self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self):", "{\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\":", "answers or the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object", "server side export for XML format and get an export_id. Args: hashes (:obj:`bool`,", "= 1 page_rows = all_rows while True: if len(all_rows or []) >= data.row_count:", "export_id. Args: leading (:obj:`str`, optional): Prepend this text to each line. Defaults to:", "5. max_poll_count (:obj:`int`, optional): If not 0, only poll N times. Defaults to:", "= now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"]", "= \"Received a page with no answers, considering all answers received\" self.log.info(m) break", "pq_tmpl = \" index: {idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl =", "considering all answers received\" m = m.format(c=data.row_count) self.log.info(m) break if not page_rows: m", "poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start", "poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5. max_poll_count", "m = m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m = \"Picking first", "parameters to sensors on the left hand side of the question.\"\"\" param_cls =", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs)", "hashes=False, **kwargs): \"\"\"Start up a server side export for XML format and get", "(:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to: 2. lvl", "SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m =", "value (:obj:`str`, optional): Value of parameter to set. Defaults to: \"\". derive_default (:obj:`bool`,", "not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def", "self.api_objects.Sensor() for key in self.params_defined: if key not in self.param_values and set_param_defaults: self.set_parameter(key=key,", "= \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\"", "sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow. lvl", "def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ):", "m = \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data = r.text if", "[err, \"Supply an index of a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise", "raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects, parameter values left:", "filter consider the value type as this. Must be one of :data:`TYPE_MAP` Defaults", "pq_tmpl.format pq_list = [] for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx,", "Have filter match all values instead of any value. Defaults to: False. type", "the answers for this question one page at a time. Args: page_size (:obj:`int`,", "cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a", "{vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\"", ":data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value =", "get_args.items()} while True: if max_page_count and page_count >= max_page_count: m = \"Reached max", "get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj", "\"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\",", "ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for this", "the value type as this. Must be one of :data:`TYPE_MAP` Defaults to: None.", "m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id", "or the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\"", "**kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start =", "Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the API keep the cache_id that", "rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" #", "= True returns ResultSetList ApiModel object. If return_dict = True returns dict. Otherwise,", "m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None sensor.parameters =", "self.log.debug(m) return m = \"Now mapping parameters for group filter: {gf}\" m =", "results returned for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text", "type in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is invalid, must be", "get_args[\"cache_id\"] = cache_id page_count = 1 m = \"Received initial page length={len}, cache_info={cache!r}\"", "@classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined: if key not in self.param_values", "Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging, which means ALL", "export_id is an XML format, return a dictionary object. Defaults to: False. return_obj", "] m = \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"]", "= sensor for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self):", "row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj)", "of rows values Defaults to: False. sleep (:obj:`int`, optional): Wait N seconds between", "Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If", "an XML format, return a dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional):", "Filter API object \"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor =", "use for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults", "expiring the cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait N seconds between", "Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList", "appended to it. If this is None, a new CacheFilterList will be created", "obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\":", "of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO:", "= self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the key", "\"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"]", "returns ResultSetList ApiModel object. If return_dict = True returns dict. Otherwise, return str.", "keys that are not in the parameters definition for this sensor to be", "cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed", "\"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\",", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] =", "def expiration(self): \"\"\"Get expiration details for this question. Returns: :obj:`dict` \"\"\" now_dt =", "pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size is not 0, have", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls,", "@property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns:", "**kwargs ): \"\"\"Get all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "for this question in XML format using server side export. Args: export_id (:obj:`str`):", "\"\"\"Set a parameters value for this sensor. Args: key (:obj:`str`): Key name of", "obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "] m = \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos", "this workflow. last_reg (:obj:`int`, optional): Only return clients that have registered in N", "lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has been asked by seeing if", "question in XML format using server side export. Args: export_id (:obj:`str`): An export", "\"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\":", "for p in params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals", "parameter to set. value (:obj:`str`, optional): Value of parameter to set. Defaults to:", "= self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the key value pairs of", "ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args =", "export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count and poll_count", "optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`.", "= m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m = \"Server Side", "status is compared against the value in last_reg. Must be one of :data:`OPERATOR_MAP`.", "parameters definition for this sensor to be set. Throws exception if False and", "to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that are", "answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m = \",", "self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV format\", \"export_id={e!r}\"]", "Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter,", "it. Args: index (:obj:`int`, optional): Index of parse result to ask. Defaults to:", "e.g. \"2 years, 3 months, 18 days, 4 hours, 22 minutes: # 'TimeDiff',", "value. Defaults to: False. type (:obj:`str`, optional): Have filter consider the value type", "(:obj:`str`): Filter sensor rows returned on this value. operator (:obj:`str`, optional): Operator to", "filters=None ): \"\"\"Build a set of filters to be used in :meth:`Clients.get_all. Args:", "rows values Defaults to: False. sleep (:obj:`int`, optional): Wait N seconds between fetching", "response for CEF format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m)", "is None and one of the parse results is an exact match, pick", "page_rows = len(paging_result_obj) received_rows += page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\",", "up a server side export for CEF format and get an export_id. Args:", "percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If not 0, wait until N", "[]: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse result indices in str", "column headers. Defaults to: True. hashes (:obj:`bool`, optional): Have the API include the", "self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs:", "str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id)", "m = \"Finished getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas =", "trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received Server Side Export", "3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6,", "return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, )", "workflow. id (:obj:`int`): id of sensor to fetch. lvl (:obj:`str`, optional): Logging level.", "map_group_params(self, pq, group): \"\"\"Map parameters to filters on the right hand side of", "\", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5,", "for param in params: if not param_values: m = \"No more parameter values", "len(all_rows or []) >= max_row_count: m = \"Hit max pages of {max_row_count}, considering", "the hashes of rows values Defaults to: False. sleep (:obj:`int`, optional): Wait N", "0, have the API keep the cache of clients for this many seconds", "= param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property", "for XML format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log", "def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor()", "self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side", "None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not", "defined, not mapping group params\" self.log.debug(m) return for group_filter in group.filters or []:", "or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\":", "\"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300,", "= adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None: m = \"No parse", "of clients from API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If not 0,", "return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export", "sensor = [x for x in group_sensors if x.id == sensor_id][0] if not", "client status is compared against the value in last_reg. Must be one of", "text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj = True", "empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters", "-*- \"\"\"Workflow encapsulation package for performing actions using the Tanium API.\"\"\" from __future__", "this workflow. id (:obj:`int`): id of sensor to fetch. lvl (:obj:`str`, optional): Logging", ":obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt =", "utf-8 -*- \"\"\"Workflow encapsulation package for performing actions using the Tanium API.\"\"\" from", "set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default value from parameter definition", "\"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object", "adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys] else: vals =", ":obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for p", "getattr(self.filter, k)) for k in keys] else: vals = [] return vals def", "{dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count:", "m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ):", "not group: m = \"Empty group, not mapping group params\" self.log.debug(m) return if", "or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs):", "{w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter, text,", "# e.g. \"2 years, 3 months, 18 days, 4 hours, 22 minutes: #", "for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the", "a server side export for XML format and get an export_id. Args: hashes", "] err = \", \".join(err) err = [err, \"Supply an index of a", "\"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for", "\"\"\"Get the parameters that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API", "pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result", "all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size is not 0,", "m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in", "# SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, #", "= \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\" data = result.str_to_obj(text=data, src=src,", "else: ret[\"expire_in\"] = ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\"", "now_pct >= poll_pct: m = \"Reached {now_pct} out of {pct}, considering all answers", "to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"]", "workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed question:", "\"Finished getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas", "str form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r}, params: {params}, exact: {exact}\"", "adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter)", "= \"Reached {now_pct} out of {pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct),", "{rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] +=", "self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl =", "- start m = \"Finished getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m)", "m = m.format(c=data.row_count) self.log.info(m) break if not page_rows: m = \"Received a page", "answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"]", "before and after parameter key name when sending to API. Defaults to: \"||\".", "+ ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str,", "cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object", "fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result", "if max_row_count and len(all_rows or []) >= max_row_count: m = \"Hit max pages", "m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up", "\"completed\": m = \"Server Side Export completed: {status}\" m = m.format(status=status) self.log.info(m) break", "Filter sensor rows returned on this value. operator (:obj:`str`, optional): Operator to use", "optional): Only fetch up to this many pages. If 0, get all pages.", "exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for idx, pq in enumerate(self.obj):", "op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds", "lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj", "= m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield obj", "status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count and poll_count >=", "infos = self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total = est_total if", "- start m = \"Finished polling for Server Side Export in {dt}, {status}\"", "{},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"):", "page_count >= max_page_count: m = \"Reached max page count {c}, considering all clients", "len(all_rows or []) >= data.row_count: m = \"Received expected row_count {c}, considering all", "API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that are not", "\".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits", "m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached", "{c}\", ] m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total,", "been asked by seeing if self.obj.id is set.\"\"\" if not self.obj.id: m =", "= [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m)", "for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional):", "break if max_row_count and len(all_rows or []) >= max_row_count: m = \"Hit max", "ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on value. Defaults to: True. not_flag", "to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0, fetch pages until a", "if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt}, considering all answers in\"", "CacheFilterList object is supplied, the last_registration filter generated by this method will be", ":obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self):", "= row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows", "def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a", "= sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList()", "def result_indexes(self): \"\"\"Get the parse result indices in str form.\"\"\" pq_tmpl = \"", "one call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this", "get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str", "(:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self):", "next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None sensor.parameters", "answers: {info.row_count}\", \"poll count: {c}\", ] m = \", \".join(m) m = m.format(dt=elapsed,", "sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values:", "sensor has parameters defined, and no value is set, try to derive the", "Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits))", "in self.params: if param.value in [\"\", None] and not allow_empty_params: m = \"Parameter", "= m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5,", "{o!r} is not one of the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys()))", "up a server side export for XML format and get an export_id. Args:", "response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src", "ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return ret", "page_result # this should catch errors where API returns result data as None", "self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed = end - start m", "now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag,", "time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting", "result_obj: yield obj if page_size: paging_get_args = {k: v for k, v in", "rows returned on this value. operator (:obj:`str`, optional): Operator to use for filter_value.", "polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\",", "group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition: m = \"No parameters defined", "\"progress\"], status_split)) status[\"export_id\"] = export_id m = [ \"Received SSE status response: path={r.request.url!r}\",", "\"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\":", ">= stop_dt: m = \"Reached stop_dt {stop_dt}, considering all answers in\" m =", "hand side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects =", "pq): \"\"\"Map parameters to sensors on the left hand side of the question.\"\"\"", "one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have the", "{p.value!r} is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if", "before we consider it invalid. 0 means to use the max age property", "in XML format using server side export. Args: export_id (:obj:`str`): An export id", "\"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll", "in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas return", "= \"Empty group, not mapping group params\" self.log.debug(m) return if not group_sensors: m", "to set. value (:obj:`str`, optional): Value of parameter to set. Defaults to: \"\".", "obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow. lvl (:obj:`str`, optional): Logging", "clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\", ] m = \",", "page_datas[0] page_rows = page_data.rows m = \"Received page #{c} answers: {rows}\" m =", "export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an XML", "def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by name. Args: adapter", "this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\"", "log.info(m) break if received_rows >= total_rows: m = \"Reached total rows count {c},", "True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"]", "values Defaults to: False. sleep (:obj:`int`, optional): Wait N seconds between fetching each", "m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m = \"Reached total rows count", "{k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for", "[\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs] bits", "\"Received page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows", "\"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated from. Defaults to:", "\"No parameters defined on sensor {s}, going to next\" m = m.format(s=sensor) self.log.debug(m)", "= m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m = \"Reached total rows", ">= max_poll_count: m = \"Reached max poll count {c}, considering all answers in\"", "max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter =", "m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end =", "] if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits =", "{ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default", "this sensor. Notes: Will try to resolve a default value and store it", "to: \"\". derive_default (:obj:`bool`, optional): Get default value from parameter definition if value", ":obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj", "loop #{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct:", "return_obj = True returns ResultSetList ApiModel object. If return_dict = True returns dict.", "rows if possible (single line in each cell) Defaults to: False. headers (:obj:`bool`,", "for groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {}", "m = [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \",", "\"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt", "a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "returned on this value. operator (:obj:`str`, optional): Operator to use for filter_value. Must", "now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed =", "if status[\"status\"] == \"failed\": m = \"Server Side Export failed: {status}\" m =", "= \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs):", "(:obj:`bool`, optional): If export_id is an XML format, return a dictionary object. Defaults", "\"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\":", ") pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse", "and self.get_canonical: pq = self.get_canonical m = \"Picking parsed question based on exact", "\".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\":", "object \"\"\" # TODO: Add wait till error_count / no_results_count == 0 self._check_id()", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not XML", "Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs)", "for CSV format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id", "Adapter to use for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from", "+= 1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj", "the expected row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id()", "**kwargs): \"\"\"Get the status for this questions server side export. Args: export_id (:obj:`str`):", "API. If 0, disables paging and gets all clients in one call. Defaults", "question. Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API", "True: poll_count += 1 if max_poll_count and poll_count >= max_poll_count: m = [", "optional): Result object that ``obj`` was generated from. Defaults to: None. \"\"\" self._lvl", "optional): Only return clients that have registered in N number of seconds. Defaults", "Logging level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter,", "the default value from each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional):", "exception. Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not", "parse results is an exact match, pick and ask it. Defaults to: True.", "CSV format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id =", "N number of seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines how the", "name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name (:obj:`str`): Name", "answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for this question", "SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj)", "\"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id,", "== \"completed\": m = \"Server Side Export completed: {status}\" m = m.format(status=status) self.log.info(m)", "= \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return", "7, # e.g. 125MB or 23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\":", "map_select_params(self, pq): \"\"\"Map parameters to sensors on the left hand side of the", "self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info.", "= end - start m = \"Finished getting {rows} answers in {dt}\" m", "ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"]", "answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll count: {c}\", ]", "param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key,", ":obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs)", ":obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\",", "poll_secs (:obj:`int`, optional): If not 0, wait until N seconds for pct of", "will be returned in one API response. For large data sets of answers,", "= \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split =", "use for this workflow. id (:obj:`int`): id of sensor to fetch. lvl (:obj:`str`,", "== 0 self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow()", "status_split = [x.strip().lower() for x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"],", "raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj =", "p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef not", "self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def", "= m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to filters", "optional): If sensor has parameters defined, and the value is not set, \"\",", "poll_count >= max_poll_count: m = \"Reached max poll count {c}, considering all answers", "clients fetched\" m = m.format(c=total_rows) log.info(m) break page_count += 1 row_start += row_count", "Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case", "cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has been asked by", "break if received_rows >= total_rows: m = \"Reached total rows count {c}, considering", "a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished", "results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data,", "the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj", "of question to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns:", ":meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging, which means ALL answers will", "parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished", "use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow.", "\"Now mapping parameters for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id =", "\"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in", "= m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for groups, parameter", "Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for", "all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info =", "to this many pages. If 0, get all pages. Defaults to: 0. max_row_count", "raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj]) m = \"Received {n}", "optional): If index is None and one of the parse results is an", "break if max_poll_count and poll_count >= max_poll_count: m = \"Reached max poll count", "= end - start m = \"Finished getting answers in {dt}\" m =", "[ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\",", "now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration)", "cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None:", "@property def params_defined(self): \"\"\"Get the parameter definitions for this sensor. Notes: Will try", "level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If", "ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", "= \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started", "page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] = row_count get_args[\"cache_expiration\"] = cache_expiration result = adapter.cmd_get(**get_args)", "\"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m = m.format( page_rows=page_rows,", "__str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))]", "value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter(", "value. Defaults to: True. not_flag (:obj:`bool`, optional): If set, negate the match. Defaults", "m = \"Reached stop_dt {stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m)", "= self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch errors where API returns", "an exact match, pick and ask it. Defaults to: True. use_first (:obj:`bool`, optional):", "adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed question: {w}\" m =", "rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow()", "of ``estimated_total`` of clients from API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If", "\"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\":", "self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None)", "set. value (:obj:`str`, optional): Value of parameter to set. Defaults to: \"\". derive_default", "lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter definitions for this sensor. Notes:", "when sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys", "self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def", "= \"Start polling loop for answers until for {o} until {stop_dt}\" m =", "XML format and get an export_id. Args: hashes (:obj:`bool`, optional): Have the API", "\"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\",", "parse results (any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter,", "not_flag (:obj:`int`, optional): If True have the API return all rows that do", "\"\"\"Get expiration details for this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td", "0, disables paging and gets all clients in one call. Defaults to: 1000.", "Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", ">= total_rows: m = \"Reached total rows count {c}, considering all clients fetched\"", "p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p) for p in params) @property def param_values(self):", "datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side export for XML", "\".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m =", "question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has", "\"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] =", "\"Finished mapping parameters for groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m)", "m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1 page_rows = all_rows", "def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text from API.", "cache_expiration (:obj:`int`, optional): Have the API keep the cache_id that is created on", "] m = \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status def", "None) get_args[\"cache_id\"] = cache_id page_count = 1 m = \"Received initial page length={len},", "value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param =", ") m = \"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return", "many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the API keep the", "each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters", "m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all answers", "that ``obj`` was generated from. Defaults to: None. \"\"\" self._lvl = lvl self.log", "Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch up to this many rows.", "now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count += 1 m", "poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5. poll_pct", "obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\"", "= \"Hit max pages of {max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count)", "and one of the parse results is an exact match, pick and ask", "for k in keys] else: vals = [] return vals def set_filter( self,", "leading (:obj:`str`, optional): Prepend this text to each line. Defaults to: \"\". trailing", "= m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\" in export_id and (return_dict", "data.row_count: m = \"Received expected row_count {c}, considering all answers received\" m =", "= get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0, fetch", "= {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if", "(:obj:`int`, optional): How old a sensor result can be before we consider it", "result() if result_obj is None: m = \"No parse results returned for text:", "None: m = \"Parameter key {o!r} is not one of the defined parameters", "of any value. Defaults to: False. type (:obj:`str`, optional): Have filter consider the", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl (:obj:`str`, optional): Logging", "[x for x in group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition: m", "r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m =", "answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self,", "False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args =", "def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "or []), dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a", "considering all answers received\" self.log.info(m) break if max_page_count and page_count >= max_page_count: m", "for group_filter in group.filters or []: if not param_values: m = \"No more", "compared against the value in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to:", "match: {em}\".format(em=True if self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits)) cls =", "page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an iterator.", "\"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\":", "max_age_seconds=0, type=None, ): \"\"\"Set a filter for this sensor to be used in", "Args: lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs:", "Append this text to each line. Defaults to: \"\". **kwargs: rest of kwargs:", "\"No more parameter values left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value", "(:obj:`str`): Question text to parse. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\" m", "object is supplied, the last_registration filter generated by this method will be appended", "operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r}", "collections import OrderedDict from . import exceptions from .. import utils from ..", "row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows =", "seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If not 0, only poll N", "(id is set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it.", "\"\"\" # TODO: Add wait till error_count / no_results_count == 0 self._check_id() cmd_args", "ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt", "from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text (:obj:`str`):", "Args: key (:obj:`str`): Key name of parameter to set. value (:obj:`str`, optional): Value", "poll N times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`.", "API keep the cache of clients for this many seconds before expiring the", "\"poll count: {c}\", ] m = \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count)", "set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the left hand side of the", "N times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns:", "fetch up to this many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have", "= \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\") if", "\"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys]", "get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag", "poll_count += 1 if max_poll_count and poll_count >= max_poll_count: m = [ \"Server", "If export_id is not XML format or return_dict and return_obj False, return the", "== sensor_id][0] if not sensor.parameter_definition: m = \"No parameters defined on sensor {s},", "of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter match all", "paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m = [ \"Received", "row_count {c}, considering all answers received\" m = m.format(c=data.row_count) self.log.info(m) break if not", "while True: if max_page_count and page_count >= max_page_count: m = \"Reached max page", "this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self, \"_filter\"): self._filter", "that happens page_datas = page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows =", "{status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m = \"Server", "Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index] m =", "workflow. text (:obj:`str`): Question text to parse. lvl (:obj:`str`, optional): Logging level. Defaults", "= ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a", "if param_def is None: m = \"Parameter key {o!r} is not one of", "parameters that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\"", "m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to", "[]) if pdef not in [\"\", None]: derived_default = pdef elif pval not", "this question. Args: hashes (:obj:`bool`, optional): Have the API include the hashes of", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not use any paging, which", "\"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args =", "SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m =", "return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data", "question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err = [ \"No index supplied\",", "v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups or []: self.map_group_params(pq,", "{d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m = \", \".join(m) m = m.format(d=data)", "_check_id(self): \"\"\"Check that question has been asked by seeing if self.obj.id is set.\"\"\"", "def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging level. Defaults", "or None, throw an exception. Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults,", ":obj:`OrderedDict` \"\"\" ret = OrderedDict() for k in self.params_defined: ret[k] = \"\" for", "status_split)) status[\"export_id\"] = export_id m = [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\",", "= text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None: m", "delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for this sensor. Args: key (:obj:`str`):", "if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m =", "if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return", "= \"Now mapping parameters for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id", "self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] =", "filter match all values instead of any value. Defaults to: False. type (:obj:`str`,", "= op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds =", ">= poll_pct: m = \"Reached {now_pct} out of {pct}, considering all answers in\"", "Defaults to: False. return_obj (:obj:`bool`, optional): If export_id is XML format, return a", "\"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod", "hashes=False, **kwargs ): \"\"\"Start up a server side export for CSV format and", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0, fetch pages", "that is created on initial get answers page alive for N seconds. Defaults", "Export start response for XML format\", \"code={c}\"] m = \", \".join(m) m =", "{!r}\".format(k, getattr(self.filter, k)) for k in keys] else: vals = [] return vals", "in get_args.items()} while True: if max_page_count and page_count >= max_page_count: m = \"Reached", "client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args)", "get data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data", "data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\" data = result.str_to_obj(text=data,", "0, only poll N times. Defaults to: 0. **kwargs: rest of kwargs: Passed", "return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers", "= filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter, filters=None,", "client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object", "import unicode_literals import datetime import json import time from collections import OrderedDict from", "side export for completion. Args: export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml`", "self.params: ret[p.key] = p.value return ret @property def params(self): \"\"\"Get the parameters that", "max_poll_count and poll_count >= max_poll_count: m = \"Reached max poll count {c}, considering", "= m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\":", "to use the max age property of the sensor. Defaults to: 0. all_values_flag", "ResultInfoList API Object \"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result", "status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m = [ \"Received SSE", "\"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", "info = infos[0] est_total = info.estimated_total poll_total = est_total if poll_total and poll_total", "= m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed,", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters (:obj:`object`, optional): Tantrum", "= adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None)", "Defaults to: 0. poll_total (:obj:`int`, optional): If not 0, wait until N clients", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1", "definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\",", "data.rows page_count = 1 page_rows = all_rows while True: if len(all_rows or [])", "= \"Parameter key {o!r} is not one of the defined parameters {ov}\" m", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args", "\"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll(", "[ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in", "OrderedDict from . import exceptions from .. import utils from .. import results", "cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or", "\"\"\"Start up a server side export for CSV format and get an export_id.", "(:obj:`str`, optional): Attribute of a ClientStatus object to have API sort the return", "return self._filter @property def filter_vals(self): \"\"\"Get the key value pairs of the filter", "this question. Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList", "filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\",", "= ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse result that", "result indices in str form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r}, params:", "m = \"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for", "not in [\"\", None]: derived_default = pval elif pvals: derived_default = pvals[0] else:", "self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter", "{info.row_count}\", \"poll count: {c}\", ] m = \", \".join(m) m = m.format(dt=elapsed, info=info,", "that are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if", "(:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls", "(:obj:`bool`, optional): Ignore case when filtering on value. Defaults to: True. not_flag (:obj:`bool`,", "operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of filters to be used in", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name (:obj:`str`): Name of", "= self.api_objects.Sensor() for key in self.params_defined: if key not in self.param_values and set_param_defaults:", "format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"]", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id of question", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"]", "cell) Defaults to: False. headers (:obj:`bool`, optional): Include column headers. Defaults to: True.", "page_size is not 0, have the API keep the cache of clients for", "= { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration:", "field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3", "times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`:", "0, wait until N seconds for pct of clients total instead of until", "= \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for", "[] for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or", "export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a server", "flatten (:obj:`bool`, optional): Flatten CSV rows if possible (single line in each cell)", "@property def result_indexes(self): \"\"\"Get the parse result indices in str form.\"\"\" pq_tmpl =", "times. Defaults to: 0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`:", "Wait N seconds between fetching each page. Defaults to: 5. **kwargs: rest of", "If 0, get all pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch", "**kwargs): \"\"\"Pick a parse result and ask it. Args: index (:obj:`int`, optional): Index", "self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters", "= now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return ret def", "for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group", "self.params.append(param) @property def filter(self): \"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter", "API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] =", "exceptions from .. import utils from .. import results class Workflow(object): def __init__(self,", "and poll_count >= max_poll_count: m = [ \"Server Side Export completed\", \"reached max", "hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\", derive_default=True,", "True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id is not", "text to parse. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest", "log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] =", "ask. Defaults to: None. use_exact_match (:obj:`bool`, optional): If index is None and one", "return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow.", "optional): If True have the API return all rows that do not match", "datas = result() self._last_datas = datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0,", "sensor for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get", "now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str =", "] m = \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count", "sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value,", "\"{value}\"}, } TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION", "\", \".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1 page_rows", "datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m = [", "values. Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This", "to: 0. max_row_count (:obj:`int`, optional): Only fetch up to this many rows. Defaults", "= \"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code: {r.status_code}\",", "Defaults to: None. use_exact_match (:obj:`bool`, optional): If index is None and one of", "exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects, parameter values left: {pv!r}\"", "self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the key value", "self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question.", "if filters is not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start", "5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count", "m = [ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed} out of {this_total}\",", "status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl)", "log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result =", "page with no answers, considering all answers received\" self.log.info(m) break if max_page_count and", "self.log.info(m) data = r.text if \"xml\" in export_id and (return_dict or return_obj): result", "pdef elif pval not in [\"\", None]: derived_default = pval elif pvals: derived_default", "and key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None)", "hand side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values =", "{\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = {", "Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs: rest of", "Args: hashes (:obj:`bool`, optional): Have the API include the hashes of rows values", "stop_dt = start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling", "set of filters to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "this workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow. lvl (:obj:`str`,", "If 0, get all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size", "key {o!r} is not one of the defined parameters {ov}\" m = m.format(o=key,", "result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m =", "= m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical m =", "clients have total instead of ``estimated_total`` of clients from API. Defaults to: 0.", "results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop for answers until for {o}", "= \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\",", "return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data class", "pq_list = [] for idx, pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text,", "all answers received\" m = m.format(c=data.row_count) self.log.info(m) break if not page_rows: m =", "and ask it. Defaults to: True. use_first (:obj:`bool`, optional): If index is None", "a ClientStatus object to have API sort the return on. Defaults to: \"last_registration\".", "the ResultInfo for this question. Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`.", "x return None def map_select_params(self, pq): \"\"\"Map parameters to sensors on the left", "parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined,", "page_count = 1 m = \"Received initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows,", "id of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "param_def = self.params_defined.get(key, None) if param_def is None: m = \"Parameter key {o!r}", "None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg)))", "Operator to use for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\".", "return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this question. Args:", "filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for", "\"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\",", "= self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2", "B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, }", "Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\"", "= m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep)", "class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format", "and ask it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\"", "is invalid, must be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m)", "negate the match. Defaults to: False. max_age_seconds (:obj:`int`, optional): How old a sensor", "in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits)", "completed\", \"reached max poll count {c}\", \"status {status}\", ] m = \", \".join(m)", "format, return a ResultSet object. Defaults to: True. **kwargs: rest of kwargs: Passed", "= Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed question: {w}\"", "self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return select class Question(Workflow): def", "= \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq", "= False if headers else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result", "self.get_canonical m = \"Picking parsed question based on exact match: {pq.question}\" m =", "in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse result", "utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter self._result = result self._last_result =", "self.obj.id: m = \"No id issued yet, ask the question!\" raise exceptions.ModuleError(m) @property", "Check for answers every N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If", "adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m =", "of a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m =", "\"\") pvals = p.get(\"values\", []) if pdef not in [\"\", None]: derived_default =", "PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP:", "bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs] bits += [atmpl(k=k,", "m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this", "ResultSetList ApiModel object. If return_dict = True returns dict. Otherwise, return str. \"\"\"", "\"Finished mapping parameters for selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m)", "{\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\":", "ask it. Defaults to: True. use_first (:obj:`bool`, optional): If index is None and", "in one call. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to", "Adapter to use for this workflow. id (:obj:`int`): id of sensor to fetch.", "\"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self,", "question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret = {", "[ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k,", "{} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1", "Defaults to: True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If export_id", "return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter definitions for", "\"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a", "cache_expiration (:obj:`int`, optional): When page_size is not 0, have the API keep the", "def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the", "to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API", "m = [\"Started Server Side for CEF format\", \"export_id={e!r}\"] m = \", \".join(m)", "poll_count += 1 m = \"New polling loop #{c} for {o}\" m =", "0, get all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size is", "a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "{info.estimated_total}\", \"poll count: {c}\", ] m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct),", "object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name", "value (:obj:`str`): Filter sensor rows returned on this value. operator (:obj:`str`, optional): Operator", "- start m = [ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated", "total_rows: m = \"Reached total rows count {c}, considering all clients fetched\" m", "parameter keys that are not in the parameters definition for this sensor to", "def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by id. Args: adapter", "while True: poll_count += 1 m = \"New polling loop #{c} for {o}\"", "(:obj:`str`, optional): Defines how the last_registered attribute of each client status is compared", "m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to filters on", "Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters", "] m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count,", "False. return_obj (:obj:`bool`, optional): If export_id is XML format, return a ResultSet object.", "@property def params(self): \"\"\"Get the parameters that are set for this sensor. Returns:", "return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ):", "\"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"]", "the cache_id that is created on initial get answers page alive for N", "that is an exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return x", "answers for this question. Args: hashes (:obj:`bool`, optional): Have the API include the", "= {k: v for k, v in get_args.items()} while True: if max_page_count and", "m = \"No parse results returned for text: {t!r}\" m = m.format(t=text) raise", ":meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO: Add wait till error_count", "= \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, ) self.log.info(m)", "refetch data for N retries if that happens page_datas = page_result() self._last_datas =", "= [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs] bits += [atmpl(k=k, v=v)", "answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question. Args: **kwargs: rest of kwargs:", "in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration},", "API response. For large data sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`:", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos =", "\"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls,", "a time from the API. If 0, disables paging and gets all clients", "result.object_obj[\"export_id\"] m = [\"Started Server Side for XML format\", \"export_id={e!r}\"] m = \",", "get an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows if possible (single", "while True: poll_count += 1 if max_poll_count and poll_count >= max_poll_count: m =", "pq.parameter_values if not group: m = \"Empty group, not mapping group params\" self.log.debug(m)", "\"\"\" self._check_id() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result", "else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"] = hashes result", "raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id", "return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side export", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned", "ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for this sensor to", "adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this question. Args: hashes (:obj:`bool`,", "= utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count += 1 m =", "Side Export start response for CEF format\", \"code={c}\"] m = \", \".join(m) m", "{params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for idx, pq in", "{ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP =", "{dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id,", "are 0, fetch pages until a page returns no answers or the expected", "lvl=self.log.level, result=result ) m = \"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m)", "def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m", "optional): Defines how the last_registered attribute of each client status is compared against", "the API. If 0, disables paging and gets all clients in one call.", "in self.params: ret[p.key] = p.value return ret @property def params(self): \"\"\"Get the parameters", "a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "this question. Args: poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults", "= result() self._last_datas = datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0,", "fetching each page. Defaults to: 5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`.", "None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id =", "Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object", "API include the hashes of rows values Defaults to: False. sleep (:obj:`int`, optional):", "obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed question: {w}\" m = m.format(w=workflow)", "1000. filters (:obj:`object`, optional): If a CacheFilterList object is supplied, the last_registration filter", "m = \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for", "not 0, have the API keep the cache of clients for this many", "If a CacheFilterList object is supplied, the last_registration filter generated by this method", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if", "\"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else False), ] bits", "for select in selects: if not param_values: m = \"No more parameter values", "as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. filters", "exact match, pick and ask it. Defaults to: True. use_first (:obj:`bool`, optional): If", "at a time. Args: page_size (:obj:`int`, optional): Size of each page to fetch", "any_canonical = any([x.question.from_canonical_text for x in result_obj]) m = \"Received {n} parse results", "are not in the parameters definition for this sensor to be set. Throws", "N seconds for pct of clients total instead of until question expiration. Defaults", "v=getattr(self.obj, attr, None)) for attr in attrs] bits += [atmpl(k=k, v=v) for k,", "result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data", "__init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "= self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info.", "\"Reached max page count {c}, considering all answers in\" m = m.format(c=max_page_count) self.log.info(m)", "any parse result that is an exact match.\"\"\" for x in self.obj: if", "Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default value from parameter definition if", "if self.obj.id: wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr,", "request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src =", "is an exact match, pick and ask it. Defaults to: True. use_first (:obj:`bool`,", "a dictionary object. Defaults to: False. return_obj (:obj:`bool`, optional): If export_id is XML", "\"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"},", "vals = [] return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False,", "this value. operator (:obj:`str`, optional): Operator to use for filter_value. Must be one", "OrderedDict() for k in self.params_defined: ret[k] = \"\" for p in self.params: ret[p.key]", "ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor", "{em}\".format(em=True if self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__)", "break page_count += 1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args)", "0. all_values_flag (:obj:`bool`, optional): Have filter match all values instead of any value.", "#{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m", "side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`,", "result can be before we consider it invalid. 0 means to use the", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id()", "all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs: rest", "x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"] = export_id m = [ \"Received", "``estimated_total`` of clients from API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If not", "Args: hashes (:obj:`bool`, optional): Have the API include the hashes of rows values.", "= pq.question.selects or [] for select in selects: if not param_values: m =", "[\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\", \"context_group\",", "m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\",", "rest of kwargs: Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj", "text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None: m =", ":data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on value.", "\"WMIDate\": 6, # e.g. \"2 years, 3 months, 18 days, 4 hours, 22", "0, wait until N clients have total instead of ``estimated_total`` of clients from", "group.sub_groups or []: self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse result indices", "yet, ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for", "max_page_count: m = \"Reached max page count {c}, considering all clients fetched\" m", "the hashes of rows values Defaults to: False. **kwargs: rest of kwargs: Passed", "raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return", "return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ):", "#{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows", "SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3 months, 18 days, 4 hours,", "def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl =", "definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined, and", "N seconds between fetching each page. Defaults to: 5. **kwargs: rest of kwargs:", "= self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers", "this question one page at a time. Args: page_size (:obj:`int`, optional): Size of", "in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must be one", "\"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any", "ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if", "group): \"\"\"Map parameters to filters on the right hand side of the question.\"\"\"", "trailing=\"\", **kwargs): \"\"\"Start up a server side export for CEF format and get", "or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000,", "Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated from.", "has parameters defined, and the value is not set, \"\", or None, throw", "group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x", "results is an exact match, pick and ask it. Defaults to: True. use_first", "of {max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1", "Side for CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m)", "cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False", "m = m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs):", "sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to: 2.", "level. Defaults to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(),", "be returned in one API response. For large data sets of answers, this", "= datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received initial", "datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter", "cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt = start + datetime.timedelta(seconds=poll_secs)", "self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers for this question.", "\"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class", "\"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower()", "optional): Check for answers every N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional):", "Side Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args)", "# SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, #", "of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on", "page_count += 1 row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies())", "level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object that ``obj`` was generated", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj = result()", "XML format or return_dict and return_obj False, return the raw text as is.", "is XML format, return a ResultSet object. Defaults to: True. **kwargs: rest of", "= results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data =", "Have the API include the hashes of rows values Defaults to: False. sleep", "answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers", "self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for", "\"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs:", "\"\"\"Get a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "pages of {max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count +=", "up to this many pages. If 0, get all pages. Defaults to: 0.", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result()", "catch errors where API returns result data as None sometimes # need to", "this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count", "question has been asked by seeing if self.obj.id is set.\"\"\" if not self.obj.id:", "\"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4,", "to: False. type (:obj:`str`, optional): Have filter consider the value type as this.", "False. sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to:", "page_size m = [ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total", "\"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m = [\"Received", "m = [\"Started Server Side for XML format\", \"export_id={e!r}\"] m = \", \".join(m)", "the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for this question.", "optional): If sensor has parameters defined, and no value is set, try to", "for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question`", "= result end = datetime.datetime.utcnow() elapsed = end - start m = \"Finished", "are set for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not", "Export start response for CEF format\", \"code={c}\"] m = \", \".join(m) m =", "exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result)", "sensor to be set. Throws exception if False and key not in :attr:`Sensor.param_keys`.", "(:obj:`bool`, optional): Have filter match all values instead of any value. Defaults to:", "in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj", "] m = \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m)", "m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for", "self return select class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\"", "Args: page_size (:obj:`int`, optional): Size of each page to fetch at a time.", "= m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed =", "{pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err = [ \"No index supplied\", \"no", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter,", "not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None) if param_def", "set, \"\", or None, throw an exception. Defaults to: True. \"\"\" select =", "parameter key name when sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional):", "m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total poll_total", "m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\": m = \"Server Side Export", "self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed =", "o=self) self.log.debug(m) if now_pct >= poll_pct: m = \"Reached {now_pct} out of {pct},", ":data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid,", "self._last_result = result m = [\"Received Server Side Export start response for XML", "question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not group:", "poll_pct (:obj:`int`, optional): Wait until the percentage of clients total is N percent.", "(return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r,", "fetching each page. Defaults to: 2. lvl (:obj:`str`, optional): Logging level. Defaults to:", "row_start += row_count paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result()", "time. Args: page_size (:obj:`int`, optional): Size of each page to fetch at a", "param_values: m = \"No more parameter values left to map\" self.log.debug(m) return sensor", "obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all", "CEF format and get an export_id. Args: leading (:obj:`str`, optional): Prepend this text", "[\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj,", "= p.get(\"value\", \"\") pvals = p.get(\"values\", []) if pdef not in [\"\", None]:", "info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects class Clients(Workflow):", "index of a parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m", "self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading if", "returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", [])", "{r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data", "\"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3 months, 18", "(:obj:`int`, optional): Index of parse result to ask. Defaults to: None. use_exact_match (:obj:`bool`,", "page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch", "a question. Args: value (:obj:`str`): Filter sensor rows returned on this value. operator", "id of question to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "{\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\":", "select.filter = self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined: if key not", "all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for this sensor to be used", "of clients total instead of until question expiration. Defaults to: 0. poll_total (:obj:`int`,", "log.info(m) for obj in result_obj: yield obj if page_size: paging_get_args = {k: v", "elif derive_default and value == \"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim,", "from __future__ import print_function from __future__ import unicode_literals import datetime import json import", "datetime.datetime.utcnow() elapsed = end - start m = [ \"Finished polling in: {dt}\",", "pages. If 0, get all pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only", "bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set", "is supplied, the last_registration filter generated by this method will be appended to", ":meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args =", "= [\"{}: {!r}\".format(k, getattr(self.filter, k)) for k in keys] else: vals = []", "derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default return OrderedDict((p[\"key\"], p)", "sets of answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id()", "time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this many", "this should catch errors where API returns result data as None sometimes #", "if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt", "m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m", "question one page at a time. Args: page_size (:obj:`int`, optional): Size of each", "{ \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\":", "\"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING", "data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m = m.format(r=r,", "object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches:", "optional): Allow parameter keys that are not in the parameters definition for this", "for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m =", "obj if page_size: paging_get_args = {k: v for k, v in get_args.items()} while", "m = \"Received a page with no answers, considering all answers received\" self.log.info(m)", "Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will", "for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map", "m = m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True,", "4 hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" #", "@classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been", "object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs =", "def api_objects(self): return self.adapter.api_objects class Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`)", "poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients for this", "this many pages. If 0, get all pages. Defaults to: 0. cache_expiration (:obj:`int`,", "**kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`)", "= m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all", "vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP:", "start response for CSV format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code)", "c=poll_count, ) self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end - start m", "if not self.obj.id: m = \"No id issued yet, ask the question!\" raise", ":meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args =", "= page_result # this should catch errors where API returns result data as", "class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format", "def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self):", "= [\"Started Server Side for CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m", "= \"Finished polling for Server Side Export in {dt}, {status}\" m = m.format(dt=elapsed,", "**kwargs): \"\"\"Start up a server side export for XML format and get an", "key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m = \"Mapped parameter {k!r}='{v}'", "against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is", "self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to filters on the right hand", "# e.g. 125MB or 23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8,", "{max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result", "use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". result", "TYPE_MAP[type] m = \"Type {o!r} is invalid, must be one of {vo}\" m", "setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result()", "= self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"]", "before expiring the cache. Defaults to: 600. sleep (:obj:`int`, optional): Wait N seconds", "for key in self.params_defined: if key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True)", "paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args:", "elif use_first: pq = self.obj[0] m = \"Picking first matching parsed question: {pq.question}\"", "means to use the max age property of the sensor. Defaults to: 0.", "= [err, \"Supply an index of a parsed result:\", self.result_indexes] err = \"\\n\".join(err)", "m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for x in group_sensors if", "x.id == sensor_id][0] if not sensor.parameter_definition: m = \"No parameters defined on sensor", "= [\"Started Server Side for XML format\", \"export_id={e!r}\"] m = \", \".join(m) m", "False. type (:obj:`str`, optional): Have filter consider the value type as this. Must", "time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end - start m", "{\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\":", "to: False. sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults", "left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq", "answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a server side export", "status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server", "[]), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick", "each line. Defaults to: \"\". trailing (:obj:`str`, optional): Append this text to each", "= \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for", "page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result", "match, pick and ask it. Defaults to: True. use_first (:obj:`bool`, optional): If index", "= json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values: m = \"No more", "return_obj False, return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or", "is not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] = row_start get_args[\"row_count\"] =", "to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index] m = \"Picking", "err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping parameters for selects,", "= [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None) result =", "+= page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \",", "Args: flatten (:obj:`bool`, optional): Flatten CSV rows if possible (single line in each", "sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if filters is", "= sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param", "\"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None))", "to: 5. poll_pct (:obj:`int`, optional): Wait until the percentage of clients total is", "and get an export_id. Args: leading (:obj:`str`, optional): Prepend this text to each", "= self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return", "= result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache,", "m = [ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients:", "22 minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" # (numeric +", "= \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj", "\"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or 23K or 34.2Gig (numeric +", "atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None))", "datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, }", "result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas = datas data", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos", "+= page_size m = [ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated", "[ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else False), ]", "and the value is not set, \"\", or None, throw an exception. Defaults", "is not 0, have the API keep the cache of clients for this", "Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "for obj in result_obj: yield obj if page_size: paging_get_args = {k: v for", "(:obj:`bool`, optional): Have the API include the hashes of rows values Defaults to:", "\", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in", "{idx}, result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = []", "client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\"", "Key name of parameter to set. value (:obj:`str`, optional): Value of parameter to", "result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to", "= m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1 page_rows = all_rows while", "self.obj = result() def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional):", "= m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the", "= \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the", "headers (:obj:`bool`, optional): Include column headers. Defaults to: True. hashes (:obj:`bool`, optional): Have", "returns result data as None sometimes # need to refetch data for N", "rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end =", "page_data = page_datas[0] page_rows = page_data.rows m = \"Received page #{c} answers: {rows}\"", "If not 0, only poll N times. Defaults to: 0. **kwargs: rest of", "result() self._last_infos = infos m = \"Received answers info: {infos}\" m = m.format(infos=infos.serialize())", "use for this workflow. text (:obj:`str`): Question text to parse. lvl (:obj:`str`, optional):", "client_args = {} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\"", "derive_default=True) for param in self.params: if param.value in [\"\", None] and not allow_empty_params:", "sensors defined, not mapping group params\" self.log.debug(m) return for group_filter in group.filters or", "125MB or 23K or 34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9,", "use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns:", "text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to", "results (any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj,", "m = \"Start polling loop for answers until for {o} until {stop_dt}\" m", "(:obj:`str`, optional): Append this text to each line. Defaults to: \"\". **kwargs: rest", "of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against", "self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params =", "in one API response. For large data sets of answers, this is unwise.", "Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object to have", "row_start = 0 row_count = page_size if filters is not None: get_args[\"cache_filters\"] =", "\"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\",", "units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT", "row count is hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start =", "pq = self.obj[index] m = \"Picking parsed question based on index {index}: {pq.question}\"", ":meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"]", "result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\":", "x in self.obj: if x.question.from_canonical_text: return x return None def map_select_params(self, pq): \"\"\"Map", "from __future__ import absolute_import from __future__ import division from __future__ import print_function from", "for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to:", "return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must be one of {vo}\"", "value from each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor", "API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text (:obj:`str`): Question", "self._last_datas = page_datas page_data = page_datas[0] page_rows = page_data.rows m = \"Received page", "generated by this method will be appended to it. If this is None,", "to have API sort the return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional):", "Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\":", "= lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter self._result", "__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__", "id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id", "False. max_age_seconds (:obj:`int`, optional): How old a sensor result can be before we", "= self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result() self.refetch() def add_left_sensor( self,", "cache_id page_count = 1 m = \"Received initial page length={len}, cache_info={cache!r}\" m =", "it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index:", "get an export_id. Args: leading (:obj:`str`, optional): Prepend this text to each line.", "object \"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash", "= \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return", "\"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value)", "self.obj.hash select.WORKFLOW = self return select class Question(Workflow): def __str__(self): \"\"\"Show object info.", "def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers", "poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args)", "sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an", "API object \"\"\" # TODO: Add wait till error_count / no_results_count == 0", "= datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting {rows} answers", "of kwargs: Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count", "and poll_count >= max_poll_count: m = \"Reached max poll count {c}, considering all", "if status[\"status\"] == \"completed\": m = \"Server Side Export completed: {status}\" m =", "Must be one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator) if", "else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop for answers until for", "\"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log =", "Only fetch up to this many pages. If 0, get all pages. Defaults", "= m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll", "all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "max_row_count (:obj:`int`, optional): Only fetch up to this many rows. Defaults to: 0.", "row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows +=", "attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj = result() self.refetch()", "(:obj:`str`, optional): Value of parameter to set. Defaults to: \"\". derive_default (:obj:`bool`, optional):", "= \"Reached max poll count {c}, considering all answers in\" m = m.format(c=max_poll_count)", "days, 4 hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\"", "workflow.refetch() return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results", "hit. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start =", "m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs): \"\"\"Get the answers", "m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m) all_rows += page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end", "= type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor", "0, fetch pages until a page returns no answers or the expected row", "ResultSet object. Defaults to: True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes:", "3 months, 18 days, 4 hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\"", "page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows = page_data.rows m = \"Received", "item in it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt", "m = \"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos", "r=\"result_set\") src = \"SSE get data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if", "= \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self,", "[]) >= max_row_count: m = \"Hit max pages of {max_row_count}, considering all answers", "m = \"Server Side Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep)", "max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for this question", "all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m = \"Reached", "received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "XML format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id =", "N clients have total instead of ``estimated_total`` of clients from API. Defaults to:", "answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side export for CEF format", "sort the return on. Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N number", "for CEF format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id", "keep the cache_id that is created on initial get answers page alive for", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args =", "out of {pct}, considering all answers in\" m = m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break", "If export_id is an XML format, return a dictionary object. Defaults to: False.", "for this workflow. text (:obj:`str`): Question text to parse. lvl (:obj:`str`, optional): Logging", "initial page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj:", "of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ] m", "= \"Received page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or [])) self.log.info(m)", "value {p.value!r} is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m)", "resolve a default value and store it in \"derived_default\" key for each parameter", "not mapping group params\" self.log.debug(m) return if not group_sensors: m = \"No question", "pq, group): \"\"\"Map parameters to filters on the right hand side of the", "params\" self.log.debug(m) return for group_filter in group.filters or []: if not param_values: m", "parameters for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor", "operator (:obj:`str`, optional): Defines how the last_registered attribute of each client status is", "Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for", "\".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False, **kwargs):", "(:obj:`str`, optional): Prepend this text to each line. Defaults to: \"\". trailing (:obj:`str`,", "= m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m = \"Picking first matching", "parse. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs:", "in group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition: m = \"No parameters", "1 if max_poll_count and poll_count >= max_poll_count: m = [ \"Server Side Export", "for this many seconds before expiring the cache. Defaults to: 600. sleep (:obj:`int`,", "polling loop for answers until for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt)", "row_count = page_size if filters is not None: get_args[\"cache_filters\"] = filters if page_size:", "\"SSE get data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data", "in result_obj: yield obj if page_size: paging_get_args = {k: v for k, v", "is set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\"", "): \"\"\"Get the answers for this question one page at a time. Args:", "Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. **kwargs: rest of kwargs:", "mapping group params\" self.log.debug(m) return for group_filter in group.filters or []: if not", "of the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else:", "{c}, considering all answers in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and", "\".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1 page_rows =", "answers, this is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start =", "[ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m)", "if value is \"\". Defaults to: True. delim (:obj:`str`, optional): String to put", "for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self, \"_filter\"):", "\"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def", "considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info", "= m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF", "class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "all of the parameter key and values. Returns: :obj:`OrderedDict` \"\"\" ret = OrderedDict()", "object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields", "to this many pages. If 0, get all pages. Defaults to: 0. cache_expiration", "= end - start m = [ \"Finished polling in: {dt}\", \"clients answered:", "\"regex\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\",", "of clients for this many seconds before expiring the cache. Defaults to: 600.", "== \"\": value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim,", "considering all answers in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows", "export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check", "sensor. Notes: Will try to resolve a default value and store it in", "result self.obj = result() self.refetch() def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add", "it. If this is None, a new CacheFilterList will be created with the", "Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl", "Defines how the last_registered attribute of each client status is compared against the", "\"Hit max pages of {max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m)", "\"TimeDiff\": 7, # e.g. 125MB or 23K or 34.2Gig (numeric + B|K|M|G|T units)", "with no answers, considering all answers received\" self.log.info(m) break if max_page_count and page_count", "= result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV format\", \"export_id={e!r}\"] m =", "= [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m = \",", "select in selects: if not param_values: m = \"No more parameter values left", "for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x", "max_page_count and max_row_count are 0, fetch pages until a page returns no answers", "keep the cache of clients for this many seconds before expiring the cache.", "\"Finished getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m)", "\"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ]", "fetch at a time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up", ":obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs):", "side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values", "{stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break if self.expiration[\"expired\"]: m", "id (:obj:`int`): id of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults", "x.question.from_canonical_text: return x return None def map_select_params(self, pq): \"\"\"Map parameters to sensors on", "\"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values: bits", "self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse", "text to each line. Defaults to: \"\". **kwargs: rest of kwargs: Passed to", "self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj =", "\"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\":", "should catch errors where API returns result data as None sometimes # need", "if self.params: select.sensor.parameters = self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash", "pvals = p.get(\"values\", []) if pdef not in [\"\", None]: derived_default = pdef", "if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all answers in\" m =", "pairs of the filter for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if", "return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result =", "\"tmpl\": \"{value}.*\"}, \"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, }", "# 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units)", ") log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter,", "total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id", "attribute of each client status is compared against the value in last_reg. Must", "allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def answers_get_info(self,", "server side export for CEF format and get an export_id. Args: leading (:obj:`str`,", "not sensor.parameter_definition: m = \"No parameters defined on sensor {s}, going to next\"", "5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3 months, 18 days,", "in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows in answers: {info.row_count}\", \"poll", "import division from __future__ import print_function from __future__ import unicode_literals import datetime import", "the last_registration filter generated by this method will be appended to it. If", "\"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] =", ". import exceptions from .. import utils from .. import results class Workflow(object):", "return for group_filter in group.filters or []: if not param_values: m = \"No", "id, lvl=\"info\"): \"\"\"Get a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "object. Defaults to: True. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Notes: If", "params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for idx, pq", "export for XML format and get an export_id. Args: hashes (:obj:`bool`, optional): Have", "the last_registered attribute of each client status is compared against the value in", "throw an exception. Defaults to: True. \"\"\" select = sensor.build_select( set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params )", ":meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] =", "question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter,", "self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return select", "ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\",", "the API include the hashes of rows values. Defaults to: False. **kwargs: rest", "= data.rows page_count = 1 page_rows = all_rows while True: if len(all_rows or", "API.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function", "\"code={r.status_code}\", \"status={status}\", ] m = \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return", "export_id and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text, request_body=r.request.body, method=r.request.method, url=r.request.url,", "by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`):", "for this sensor. Args: key (:obj:`str`): Key name of parameter to set. value", "def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side export for XML format", "side export for CSV format and get an export_id. Args: flatten (:obj:`bool`, optional):", "= result m = [\"Received Server Side Export start response for CEF format\",", "\"\"\"Get all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "page to fetch at a time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only", "(:obj:`int`, optional): Only fetch up to this many pages. If 0, get all", "use for this workflow. name (:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`,", "pq.question_group_sensors param_values = pq.parameter_values if not group: m = \"Empty group, not mapping", "idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None,", "value = param_def.get(\"derived_default\", \"\") key_delim = \"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param)", "get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "wait until N clients have total instead of ``estimated_total`` of clients from API.", "server side export for completion. Args: export_id (:obj:`str`): An export id returned from", "OrderedDict((p[\"key\"], p) for p in params) @property def param_values(self): \"\"\"Get all of the", "Returns: :obj:`object`: ResultInfoList API object \"\"\" # TODO: Add wait till error_count /", "level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(),", "from . import exceptions from .. import utils from .. import results class", "\"reached max poll count {c}\", \"status {status}\", ] m = \", \".join(m) m", "key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter for", "in params: if not param_values: m = \"No more parameter values left to", "filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self,", "name, lvl=\"info\"): \"\"\"Get a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "must be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type):", "SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g.", "poll_total <= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0", "format and get an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows if", "map\" self.log.debug(m) return m = \"Now mapping parameters for group filter: {gf}\" m", "adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build a set of filters to be", "Value of parameter to set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default", "Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this many pages.", "be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when", "[\"Received Server Side Export start response for CEF format\", \"code={c}\"] m = \",", "self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the", "m = \"Empty group, not mapping group params\" self.log.debug(m) return if not group_sensors:", "Side Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status def", "origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get data response\"", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten", "for p in params) @property def param_values(self): \"\"\"Get all of the parameter key", "self.params_defined: if key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in", "None]: derived_default = pdef elif pval not in [\"\", None]: derived_default = pval", "selects: if not param_values: m = \"No more parameter values left to map\"", "= self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed = end - start", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. text (:obj:`str`): Question text to", "lvl=\"info\"): \"\"\"Get a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "= \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return", "import json import time from collections import OrderedDict from . import exceptions from", "sleep=5, **kwargs ): \"\"\"Get the answers for this question one page at a", "Server Side for XML format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id)", "for x in result_obj]) m = \"Received {n} parse results (any exact match:", "result_indexes(self): \"\"\"Get the parse result indices in str form.\"\"\" pq_tmpl = \" index:", "optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`.", "CEF format\", \"code={c}\"] m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id =", "or [] for select in selects: if not param_values: m = \"No more", "# SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years, 3 months, 18 days, 4", "the percentage of clients total is N percent. Defaults to: 99. poll_secs (:obj:`int`,", "in \"derived_default\" key for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs =", "instead of until question expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If not", "continue sensor.source_id = sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"]", "m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value ==", "number of clients at a time from the API. If 0, disables paging", "\", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get", "= adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows += page_rows m", "Side Export start response for CSV format\", \"code={c}\"] m = \", \".join(m) m", "object. If return_dict = True returns dict. Otherwise, return str. \"\"\" self._check_id() client_args", "question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or [] for", "if not page_rows: m = \"Received a page with no answers, considering all", "cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as an iterator. Args: adapter", "import results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter", "\"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ] m", "return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side export for", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. name (:obj:`str`): Name of sensor to", "is unwise. Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args", "sensor has parameters defined, and the value is not set, \"\", or None,", "self.filter.operator]): keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals", "and ask it. Args: index (:obj:`int`, optional): Index of parse result to ask.", "{stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total", "match, pick the first parse result and ask it. **kwargs: rest of kwargs:", "None, a new CacheFilterList will be created with the last_registration filter being the", "**kwargs ): \"\"\"Get the answers for this question one page at a time.", "\"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and ask", "self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m", "m = \"Received page #{c} answers: {rows}\" m = m.format(c=page_count, rows=len(page_rows or []))", "page. Defaults to: 5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If", "3.67 seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, #", "(:obj:`bool`, optional): Allow parameter keys that are not in the parameters definition for", "= \"Reached total rows count {c}, considering all clients fetched\" m = m.format(c=total_rows)", "= self.params select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW", "\"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1 m = \"Received initial page", "def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result self.obj", "How old a sensor result can be before we consider it invalid. 0", "a time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten else", "[x.strip().lower() for x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\", \"progress\"], status_split)) status[\"export_id\"]", "that question has been asked by seeing if self.obj.id is set.\"\"\" if not", "): \"\"\"Get all Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients.", "(:obj:`int`, optional): If not 0, only poll N times. Defaults to: 0. **kwargs:", "= infos[0] est_total = info.estimated_total poll_total = est_total if poll_total and poll_total <=", "m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield obj if page_size:", "Defaults to: \"regex\". ignore_case_flag (:obj:`bool`, optional): Ignore case when filtering on value. Defaults", "for N retries if that happens page_datas = page_result() self._last_datas = page_datas page_data", "+ B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12,", "result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. obj (:obj:`tantrum.api_models.ApiModel`):", "{s}, going to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id", "bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls,", ":obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls,", "failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end =", "(:obj:`str`): Key name of parameter to set. value (:obj:`str`, optional): Value of parameter", "received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def", "max_page_count: m = \"Reached max page count {c}, considering all answers in\" m", "return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for this question in XML format", "by this method will be appended to it. If this is None, a", "client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split", "return_obj (:obj:`bool`, optional): If export_id is XML format, return a ResultSet object. Defaults", "the filter for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]):", "result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def", "\"\"\" ret = OrderedDict() for k in self.params_defined: ret[k] = \"\" for p", "= self.obj.hash select.WORKFLOW = self return select class Question(Workflow): def __str__(self): \"\"\"Show object", "now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result", "export for CEF format and get an export_id. Args: leading (:obj:`str`, optional): Prepend", "\"RegexMatch\", \"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"},", "hours\" # (numeric + \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or 23K", "default value from parameter definition if value is \"\". Defaults to: True. delim", "{o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info =", "hashes (:obj:`bool`, optional): Have the API include the hashes of rows values Defaults", "pq = self.obj[0] m = \"Picking first matching parsed question: {pq.question}\" m =", "sometimes # need to refetch data for N retries if that happens page_datas", "for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`,", "clients for this many seconds before expiring the cache. Defaults to: 600. sleep", "If return_dict = True returns dict. Otherwise, return str. \"\"\" self._check_id() client_args =", "while True: if len(all_rows or []) >= data.row_count: m = \"Received expected row_count", "= len(paging_result_obj) received_rows += page_rows m = [ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ]", "not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for this sensor to be", "status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export for", "[ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\", \"estimated total clients: {d.estimated_total}\", ]", "pq = self.get_canonical m = \"Picking parsed question based on exact match: {pq.question}\"", "\"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse", "to: \"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result)", "= \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls,", "return a ResultSet object. Defaults to: True. **kwargs: rest of kwargs: Passed to", "m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0,", "OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"},", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {}", ":meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5.", "optional): Wait N seconds between fetching each page. Defaults to: 2. lvl (:obj:`str`,", "= \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or self.param_values:", "String to put before and after parameter key name when sending to API.", "\"Reached expiration {expiration}, considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if", "params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\", \"\") pvals = p.get(\"values\", [])", "0. max_row_count (:obj:`int`, optional): Only fetch up to this many rows. Defaults to:", "= hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas =", "page_size if filters is not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"] =", "parameters for groups, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args =", "self.log.info(m) break if max_page_count and page_count >= max_page_count: m = \"Reached max page", "op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt +", "\"status={status}\", ] m = \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status", "in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >= max_poll_count: m", "self.obj.id is set.\"\"\" if not self.obj.id: m = \"No id issued yet, ask", "param_defs = json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for p in params:", "server side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`. return_dict", "\"\"\"Get the parse result indices in str form.\"\"\" pq_tmpl = \" index: {idx},", "to: \"\". trailing (:obj:`str`, optional): Append this text to each line. Defaults to:", "= \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1", "in [\"\", None]: derived_default = pdef elif pval not in [\"\", None]: derived_default", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if", "is not XML format or return_dict and return_obj False, return the raw text", "for answers from clients for this question. Args: poll_sleep (:obj:`int`, optional): Check for", "result that is an exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text: return", "self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters for groups, parameter values left:", "exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed = end - start", "If sensor has parameters defined, and no value is set, try to derive", "Have the API keep the cache_id that is created on initial get answers", "of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if", "# SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\": 4, #", "= \"Finished mapping parameters for selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values)", "adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object by", "question to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question`", "page_datas = page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows = page_data.rows m", "= m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args)", "= m.format(pq=pq) self.log.info(m) else: err = [ \"No index supplied\", \"no exact matching", "result() self._last_datas = datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900,", "defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m)", "optional): If export_id is an XML format, return a dictionary object. Defaults to:", "return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has been asked", "= max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter", "property of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter match", "in\" m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct", "\"{d}{key}{d}\".format(d=delim, key=key) param = self.api_objects.Parameter(key=key_delim, value=value) self.params.append(param) @property def filter(self): \"\"\"Get the filter", "filter(self): \"\"\"Get the filter for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\"", "\"Empty group, not mapping group params\" self.log.debug(m) return if not group_sensors: m =", "SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES", "this many pages. If 0, get all pages. Defaults to: 0. max_row_count (:obj:`int`,", "m = \"Parameter key {o!r} is not one of the defined parameters {ov}\"", "= start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop", "5. poll_pct (:obj:`int`, optional): Wait until the percentage of clients total is N", "total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls,", "m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id sensor = [x for x in", "= self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or [] for select in", "ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined or", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id of sensor to", "export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV format\", \"export_id={e!r}\"] m", "= row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result =", "m = \", \".join(m) m = m.format( now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct), info=info, this_total=this_total, c=poll_count, )", "+= [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return", "= datetime.datetime.utcnow() cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result", "export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side export for", "end - start m = \"Finished polling for Server Side Export in {dt},", "If return_obj = True returns ResultSetList ApiModel object. If return_dict = True returns", "{pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result", "\"code: {r.status_code}\", \"export_id: {e!r}\"] m = \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m)", "optional): Flatten CSV rows if possible (single line in each cell) Defaults to:", "else: vals = [] return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False,", "from .. import utils from .. import results class Workflow(object): def __init__(self, adapter,", "the parameters definition for this sensor to be set. Throws exception if False", "= self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined: if", "self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if not param_values: m =", "# this should catch errors where API returns result data as None sometimes", "= infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct} out", "get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if filters is not", "pages until a page returns no answers or the expected row count is", "datas = result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"]", "\"BESDate\": 4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2", "parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"]", "is \"\". Defaults to: True. delim (:obj:`str`, optional): String to put before and", "value type as this. Must be one of :data:`TYPE_MAP` Defaults to: None. \"\"\"", "for attr in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result =", "m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical = any([x.question.from_canonical_text for x in result_obj]) m", "Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl (:obj:`str`,", "optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl)", "m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params", "m = \"Reached max poll count {c}, considering all answers in\" m =", "adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs: rest of kwargs: Passed", "up a server side export for CSV format and get an export_id. Args:", "\", \".join(err) err = [err, \"Supply an index of a parsed result:\", self.result_indexes]", "for this sensor. Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys =", "parameters for selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group)", "= ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new", "= \"Finished getting answers in {dt}\" m = m.format(dt=elapsed) self.log.info(m) datas = result()", "parse result that is an exact match.\"\"\" for x in self.obj: if x.question.from_canonical_text:", "adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None: m = \"No parse results", "= getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count", "left hand side of the question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults", "0 while True: poll_count += 1 m = \"New polling loop #{c} for", "an export_id. Args: leading (:obj:`str`, optional): Prepend this text to each line. Defaults", "set.\"\"\" if not self.obj.id: m = \"No id issued yet, ask the question!\"", "retries if that happens page_datas = page_result() self._last_datas = page_datas page_data = page_datas[0]", "0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"] = hashes result =", "clients from API. Defaults to: 0. max_poll_count (:obj:`int`, optional): If not 0, only", "answers in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or [])", "data as None sometimes # need to refetch data for N retries if", "{\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\":", "def add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the left", "for k, v in get_args.items()} while True: if max_page_count and page_count >= max_page_count:", "= ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type =", "Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl,", "is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`: If return_obj = True returns ResultSetList", "minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2 hours\" # (numeric + \"Y|MO|W|D|H|M|S\"", "adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self): \"\"\"Check that question has been", "expiration(self): \"\"\"Get expiration details for this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow()", "text to each line. Defaults to: \"\". trailing (:obj:`str`, optional): Append this text", "= \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter,", "infos = result() self._last_infos = infos m = \"Received answers info: {infos}\" m", "(:obj:`bool`, optional): Flatten CSV rows if possible (single line in each cell) Defaults", "answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export for completion. Args:", "\"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def", "questions server side export. Args: export_id (:obj:`str`): An export id returned from :meth:`sse_start`.", "= {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count +=", "\"contains\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}.*\"}, \"hash\": {\"op\": \"HashMatch\", \"tmpl\": \"{value}\"}, } TYPE_MAP =", "answers page alive for N seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have", "index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and ask it. Args: index", "\"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__() @property def api_objects(self): return self.adapter.api_objects", "N seconds between fetching each page. Defaults to: 2. lvl (:obj:`str`, optional): Logging", "is None, a new CacheFilterList will be created with the last_registration filter being", "to: True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined, and the value", "cmd_args[\"export_format\"] = 3 if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else", "last_registered attribute of each client status is compared against the value in last_reg.", "cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result infos = result() self._last_infos", "to the left hand side of the question. Args: sensor (:obj:`Sensor`): Sensor workflow", "derived_default return OrderedDict((p[\"key\"], p) for p in params) @property def param_values(self): \"\"\"Get all", "\"Start polling loop for answers until for {o} until {stop_dt}\" m = m.format(o=self,", "data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\"", "fetched\" m = m.format(c=total_rows) log.info(m) break page_count += 1 row_start += row_count paging_get_args[\"row_start\"]", "= result() self._last_datas = datas data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] +=", "def map_select_params(self, pq): \"\"\"Map parameters to sensors on the left hand side of", "parse result and ask it. Args: index (:obj:`int`, optional): Index of parse result", "max_page_count (:obj:`int`, optional): Only fetch up to this many pages. If 0, get", "poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side export for completion. Args: export_id (:obj:`str`):", "a time. Args: page_size (:obj:`int`, optional): Size of each page to fetch at", "sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in", "allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and value == \"\": value =", "ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters", "**kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "sensors on the left hand side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values", "in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self,", "export_id is XML format, return a ResultSet object. Defaults to: True. **kwargs: rest", "m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m = \"Picking first matching parsed", "answers every N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If not 0,", "if False and key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def =", "parsed result\", \"and use_first is False!\", ] err = \", \".join(err) err =", "is an XML format, return a dictionary object. Defaults to: False. return_obj (:obj:`bool`,", "Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) def _check_id(self):", "def params_defined(self): \"\"\"Get the parameter definitions for this sensor. Notes: Will try to", "m = m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups", "of parameter to set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default value", "bits += [atmpl(k=k, v=v) for k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n", "data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def", "pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list)", "= adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters or adapter.api_objects.CacheFilterList()", "details for this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta()", "= 0 while True: poll_count += 1 m = \"New polling loop #{c}", "if not param_values: m = \"No more parameter values left to map\" self.log.debug(m)", "self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for", "Will try to resolve a default value and store it in \"derived_default\" key", "each page. Defaults to: 5. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes:", ":obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get", "= 0 row_count = page_size if filters is not None: get_args[\"cache_filters\"] = filters", "get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m =", "= param_defs.get(\"parameters\", []) for p in params: pdef = p.get(\"defaultValue\", \"\") pval =", "for this question. Returns: :obj:`dict` \"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret", "= result() def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging", "Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields:", "is not set, \"\", or None, throw an exception. Defaults to: True. \"\"\"", "True. not_flag (:obj:`bool`, optional): If set, negate the match. Defaults to: False. max_age_seconds", "hashes of rows values Defaults to: False. sleep (:obj:`int`, optional): Wait N seconds", "None) if param_def is None: m = \"Parameter key {o!r} is not one", "set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter", "to use for this workflow. name (:obj:`str`): Name of sensor to fetch. lvl", "workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields", "= cache_id page_count = 1 m = \"Received initial page length={len}, cache_info={cache!r}\" m", "for Server Side Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return", "An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an", "flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a server side export for CSV", "to: 5. max_poll_count (:obj:`int`, optional): If not 0, only poll N times. Defaults", "result: {text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for", "which means ALL answers will be returned in one API response. For large", "\"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}: {!r}\".format(k, getattr(self.filter, k)) for", "it. Defaults to: True. use_first (:obj:`bool`, optional): If index is None and there", "package for performing actions using the Tanium API.\"\"\" from __future__ import absolute_import from", "in attrs] bits += [atmpl(k=k, v=v) for k, v in self.expiration.items()] bits =", "break if max_page_count and page_count >= max_page_count: m = \"Reached max page count", "\"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt =", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. id (:obj:`int`): id of", "True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] =", "workflow. obj (:obj:`tantrum.api_models.ApiModel`): API Object to use for this workflow. lvl (:obj:`str`, optional):", "max_poll_count=0, **kwargs): \"\"\"Poll a server side export for completion. Args: export_id (:obj:`str`): An", "selects = pq.question.selects or [] for select in selects: if not param_values: m", "{n} parse results (any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return", "status[\"export_id\"] = export_id m = [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\",", "select.sensor.source_id = self.obj.id select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self", "m = \"Hit max pages of {max_row_count}, considering all answers received\" m =", "\"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2, # SENSOR_RESULT_TYPE_NUMERIC \"NumericDecimal\": 3, # SENSOR_RESULT_TYPE_DATE_BES \"BESDate\":", "allow_undefined=True ): \"\"\"Set a parameters value for this sensor. Args: key (:obj:`str`): Key", "XML format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id", "**kwargs): \"\"\"Start up a server side export for CEF format and get an", "sensor.id = None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params:", "= pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def", "{\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\": \"RegexMatch\", \"tmpl\":", "\"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text result", "Wait until the percentage of clients total is N percent. Defaults to: 99.", "to: 99. poll_secs (:obj:`int`, optional): If not 0, wait until N seconds for", "cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 3 if flatten else 0", "Server Side Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status", "to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id = sensor.id sensor.id = None", "cache_expiration result = adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache = getattr(result_obj,", "TODO: Add wait till error_count / no_results_count == 0 self._check_id() cmd_args = {}", "not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type def build_select(self, set_param_defaults=True,", "False and key not in :attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key,", "encapsulation package for performing actions using the Tanium API.\"\"\" from __future__ import absolute_import", "or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every N seconds. Defaults to:", "client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m", "matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err = [ \"No", "If sensor has parameters defined, and the value is not set, \"\", or", "if index: pq = self.obj[index] m = \"Picking parsed question based on index", "each cell) Defaults to: False. headers (:obj:`bool`, optional): Include column headers. Defaults to:", "def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m", "\"last_registration\". page_size (:obj:`int`, optional): Get N number of clients at a time from", "- start m = \"Finished getting {rows} answers in {dt}\" m = m.format(rows=len(all_rows", "last_registration filter being the only item in it. Defaults to: None. Returns: :obj:`Clients`", "units) \"TimeDiff\": 7, # e.g. 125MB or 23K or 34.2Gig (numeric + B|K|M|G|T", "m = \"Reached expiration {expiration}, considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m)", "parse result and ask it. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns:", "adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text from API. Args: adapter", "API Object to use for this workflow. lvl (:obj:`str`, optional): Logging level. Defaults", "= self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\") if x.strip()] status =", "max page count {c}, considering all clients fetched\" m = m.format(c=max_page_count) log.info(m) break", "parse(cls, adapter, text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text from API. Args:", "or \"{}\") params = param_defs.get(\"parameters\", []) for p in params: pdef = p.get(\"defaultValue\",", "wait until N seconds for pct of clients total instead of until question", "considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count", "a server side export for CSV format and get an export_id. Args: flatten", "not mapping group params\" self.log.debug(m) return for group_filter in group.filters or []: if", "type (:obj:`str`, optional): Have filter consider the value type as this. Must be", "to use for this workflow. filters (:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`.", "each page. Defaults to: 2. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\".", "utils from .. import results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None):", "+= page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end - start m =", "in keys] else: vals = [] return vals def set_filter( self, value, operator=\"regex\",", "paging_get_args[\"row_start\"] = row_start paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj)", "total clients: {d.estimated_total}\", ] m = \", \".join(m) m = m.format(d=data) self.log.info(m) all_rows", "def get_canonical(self): \"\"\"Return any parse result that is an exact match.\"\"\" for x", "__future__ import unicode_literals import datetime import json import time from collections import OrderedDict", "on the right hand side of the question.\"\"\" param_cls = self.api_objects.Parameter group_sensors =", "now_td, \"expired\": True, } if self.obj.expiration: ex_dt = self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >=", "to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def get_by_id(cls, adapter,", "0, get all pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch up", "optional): String to put before and after parameter key name when sending to", "select class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl =", "Defaults to: 5. max_poll_count (:obj:`int`, optional): If not 0, only poll N times.", "cmd_args.update(kwargs) cmd_args[\"text\"] = text result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is", "index: pq = self.obj[index] m = \"Picking parsed question based on index {index}:", "@property def param_values(self): \"\"\"Get all of the parameter key and values. Returns: :obj:`OrderedDict`", "line in each cell) Defaults to: False. headers (:obj:`bool`, optional): Include column headers.", "m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj", "Wait N seconds between fetching each page. Defaults to: 2. lvl (:obj:`str`, optional):", "poll_pct: m = \"Reached {now_pct} out of {pct}, considering all answers in\" m", "issued yet, ask the question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details", "answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >= max_poll_count:", "url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE get", "wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result self.obj =", "mapping parameters for selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq,", "{o!r} is invalid, must be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise", "{ \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\": now_td, \"expired\": True, } if self.obj.expiration: ex_dt", "instead of ``estimated_total`` of clients from API. Defaults to: 0. max_poll_count (:obj:`int`, optional):", "now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if is_ex: ret[\"expire_ago\"] =", "sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If sensor has parameters defined,", "cmd_args[\"row_start\"] += page_size m = [ \"Received initial answers: {d.rows}\", \"expected row_count: {d.row_count}\",", "m = \"Picking parsed question based on index {index}: {pq.question}\" m = m.format(index=index,", "self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side export", "= m.format(w=workflow) self.log.info(m) workflow.refetch() return workflow @classmethod def parse(cls, adapter, text, lvl=\"info\", **kwargs):", "page_count = 1 page_rows = all_rows while True: if len(all_rows or []) >=", "self.log.info(m) break if not page_rows: m = \"Received a page with no answers,", "attr in wipe_attrs: setattr(self.obj, attr, None) result = self.adapter.cmd_add(obj=self.obj, **kwargs) self._last_result = result", "left to map\" self.log.debug(m) return m = \"Now mapping parameters for group filter:", "the API return all rows that do not match the operator. Defaults to:", "m = \"Received expected row_count {c}, considering all answers received\" m = m.format(c=data.row_count)", "defined, and the value is not set, \"\", or None, throw an exception.", "m.format( page_rows=page_rows, received_rows=received_rows, total_rows=total_rows, ) log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep)", "adapter.cmd_get(**get_args) result_obj = result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows", "self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show", "self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m", "= poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True: poll_count +=", "= \"No more parameter values left to map\" self.log.debug(m) return m = \"Now", "hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter() self._filter.sensor = self.api_objects.Sensor() self._filter.sensor.hash = self.obj.hash return self._filter", "parameters defined, and no value is set, try to derive the default value", "@classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by id. Args:", "parse result indices in str form.\"\"\" pq_tmpl = \" index: {idx}, result: {text!r},", "type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor =", "obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the parameter definitions for this sensor.", "sensor. Args: key (:obj:`str`): Key name of parameter to set. value (:obj:`str`, optional):", "result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed = end -", "0. **kwargs: rest of kwargs: Passed to :meth:`answers_get_info`. Returns: :obj:`object`: ResultInfoList API object", "34.2Gig (numeric + B|K|M|G|T units) \"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11,", "all values instead of any value. Defaults to: False. type (:obj:`str`, optional): Have", "parse results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "no exact match, pick the first parse result and ask it. **kwargs: rest", "src = \"SSE get data response\" data = result.str_to_obj(text=data, src=src, try_int=False) if return_dict:", "\"\"\"Workflow encapsulation package for performing actions using the Tanium API.\"\"\" from __future__ import", "] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def", "try to derive the default value from each parameters definition. Defaults to: True.", "export_id, return_dict=False, return_obj=True, **kwargs ): \"\"\"Get the answers for this question in XML", "Defaults to: True. allow_empty_params (:obj:`bool`, optional): If sensor has parameters defined, and the", "param_values: m = \"No more parameter values left to map\" self.log.debug(m) return m", "[\"Received Server Side Export start response for CSV format\", \"code={c}\"] m = \",", "data = r.text if \"xml\" in export_id and (return_dict or return_obj): result =", "match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first: pq = self.obj[0] m =", "if len(all_rows or []) >= data.row_count: m = \"Received expected row_count {c}, considering", "id, lvl=\"info\"): \"\"\"Get a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow", "old a sensor result can be before we consider it invalid. 0 means", "[] return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None,", "case when filtering on value. Defaults to: True. not_flag (:obj:`bool`, optional): If set,", "Defaults to: 0. cache_expiration (:obj:`int`, optional): When page_size is not 0, have the", "[atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr in attrs] bits += [atmpl(k=k, v=v) for", "(:obj:`int`, optional): If not 0, wait until N seconds for pct of clients", "start + datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop for", "info.estimated_total poll_total = est_total if poll_total and poll_total <= est_total: this_total = poll_total", "data = datas[0] cmd_args[\"cache_id\"] = data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received", "= m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV", "initial get answers page alive for N seconds. Defaults to: 900. hashes (:obj:`bool`,", "to: False. max_age_seconds (:obj:`int`, optional): How old a sensor result can be before", "poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients for", "to: 1000. filters (:obj:`object`, optional): If a CacheFilterList object is supplied, the last_registration", "ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds = max_age_seconds self.filter.value_type = type", "info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\",", "and get an export_id. Args: hashes (:obj:`bool`, optional): Have the API include the", "if self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return", "returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers", "attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id: wipe_attrs = [\"id\",", "get an export_id. Args: hashes (:obj:`bool`, optional): Have the API include the hashes", "result self.obj = result() def ask(self, **kwargs): \"\"\"Ask the question. Args: lvl (:obj:`str`,", "on index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match and self.get_canonical:", "x in result_obj]) m = \"Received {n} parse results (any exact match: {ac})\"", "if type in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r} is invalid, must", "Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter match all values instead of", "for attr in attrs] bits += [atmpl(k=k, v=v) for k, v in self.expiration.items()]", "\"\"\"Ask the question. Args: lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs:", "Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj", "self.params_defined: ret[k] = \"\" for p in self.params: ret[p.key] = p.value return ret", "the answers for this question in XML format using server side export. Args:", ":obj:`Question` \"\"\" if index: pq = self.obj[index] m = \"Picking parsed question based", "the API keep the cache_id that is created on initial get answers page", "for answers every N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If not", "pages. If 0, get all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional): When", "filters (:obj:`object`, optional): If a CacheFilterList object is supplied, the last_registration filter generated", "consider it invalid. 0 means to use the max age property of the", "for answers every N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until", "and page_count >= max_page_count: m = \"Reached max page count {c}, considering all", "key (:obj:`str`): Key name of parameter to set. value (:obj:`str`, optional): Value of", "wipe_attrs = [\"id\", \"context_group\", \"management_rights_group\"] for attr in wipe_attrs: setattr(self.obj, attr, None) result", "infos = self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [", "\"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical", "question group sensors defined, not mapping group params\" self.log.debug(m) return for group_filter in", "select.filter.sensor.id = self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return select class", "all pages. Defaults to: 0. max_row_count (:obj:`int`, optional): Only fetch up to this", "= result() if result_obj is None: m = \"No parse results returned for", "answers for this question one page at a time. Args: page_size (:obj:`int`, optional):", "optional): How old a sensor result can be before we consider it invalid.", "= m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result #", ":meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index] m = \"Picking parsed", "CSV format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id", "export_id (:obj:`str`): An export id returned from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id", "\"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def get_by_name(cls, adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by", "add_left_sensor( self, sensor, set_param_defaults=True, allow_empty_params=False ): \"\"\"Add a sensor to the left hand", "\"Picking parsed question based on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif", "ResultInfo for this question. Args: **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns:", "consider the value type as this. Must be one of :data:`TYPE_MAP` Defaults to:", "parameters to filters on the right hand side of the question.\"\"\" param_cls =", "used in a question. Args: value (:obj:`str`): Filter sensor rows returned on this", "est_total = info.estimated_total poll_total = est_total if poll_total and poll_total <= est_total: this_total", "\"\"\"Get the parameter definitions for this sensor. Notes: Will try to resolve a", "status for this questions server side export. Args: export_id (:obj:`str`): An export id", "self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or [] for select in selects:", "to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs)", "{\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\":", "of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "= self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m", "\"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits)", "asked by seeing if self.obj.id is set.\"\"\" if not self.obj.id: m = \"No", "will not use any paging, which means ALL answers will be returned in", ">= max_page_count: m = \"Reached max page count {c}, considering all clients fetched\"", "Adapter to use for this workflow. **kwargs: rest of kwargs: Passed to :meth:`Clients.get_all_iter`.", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 1 cmd_args[\"include_hashes_flag\"]", "(:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact", "return clients that have registered in N number of seconds. Defaults to: 300.", "(:obj:`bool`, optional): If export_id is XML format, return a ResultSet object. Defaults to:", "results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\", result=None): \"\"\"Constructor. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "def pick(self, index=None, use_exact_match=True, use_first=False, **kwargs): \"\"\"Pick a parse result and ask it.", "seconds. Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until the percentage of clients", "paging_get_args = {k: v for k, v in get_args.items()} while True: if max_page_count", "= \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break if status[\"status\"] == \"completed\":", "= [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals = [\"{}:", "self.log.debug(m) return status def answers_sse_poll(self, export_id, poll_sleep=5, max_poll_count=0, **kwargs): \"\"\"Poll a server side", "m.format(d=data) self.log.info(m) all_rows = data.rows page_count = 1 page_rows = all_rows while True:", "data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow):", "to: None. \"\"\" self._lvl = lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj", "sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional): Have filter match all values instead", "from :meth:`sse_start`. return_dict (:obj:`bool`, optional): If export_id is an XML format, return a", "mapping parameters for group filter: {gf}\" m = m.format(gf=group_filter) self.log.debug(m) sensor_id = group_filter.sensor.id", "months, 18 days, 4 hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\" or", "years, 3 months, 18 days, 4 hours, 22 minutes: # 'TimeDiff', and 3.67", "from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every", "keys = [ \"operator\", \"value\", \"ignore_case_flag\", \"not_flag\", \"all_values_flag\", \"max_age_seconds\", \"value_type\", ] vals =", "param_cls = self.api_objects.Parameter param_values = pq.parameter_values selects = pq.question.selects or [] for select", "\"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"},", "= page_result() self._last_datas = page_datas page_data = page_datas[0] page_rows = page_data.rows m =", "= hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow() elapsed =", "key in self.params_defined: if key not in self.param_values and set_param_defaults: self.set_parameter(key=key, derive_default=True) for", "= \"Server Side Export completed: {status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"]", "use for this workflow. id (:obj:`int`): id of question to fetch. lvl (:obj:`str`,", "group_filter.sensor = sensor for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group) @property def", "= get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag =", "the left hand side of the question.\"\"\" param_cls = self.api_objects.Parameter param_values = pq.parameter_values", "to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value)) m", "pq_tmpl = pq_tmpl.format pq_list = [] for idx, pq in enumerate(self.obj): pq_txt =", "not set, \"\", or None, throw an exception. Defaults to: True. \"\"\" select", "self.log.debug(m) if now_pct >= poll_pct: m = \"Reached {now_pct} out of {pct}, considering", "= datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\": now_td, \"expire_ago\":", "sensor.source_id = sensor.id sensor.id = None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for", "if result_obj is None: m = \"No parse results returned for text: {t!r}\"", "(:obj:`bool`, optional): If index is None and there is no exact match, pick", "def new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "= [ \"No index supplied\", \"no exact matching parsed result\", \"and use_first is", "result_obj]) m = \"Received {n} parse results (any exact match: {ac})\" m =", "If 0, disables paging and gets all clients in one call. Defaults to:", "= derived_default return OrderedDict((p[\"key\"], p) for p in params) @property def param_values(self): \"\"\"Get", "elapsed = end - start m = \"Finished getting {rows} answers in {dt}\"", "m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this", "parameters defined on sensor {s}, going to next\" m = m.format(s=sensor) self.log.debug(m) continue", "the value in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag", "a sensor result can be before we consider it invalid. 0 means to", ":meth:`tantrum.adapter.Adapter.cmd_add`. Notes: If question has already been asked (id is set), we wipe", "pq in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), )", "matching parsed result\", \"and use_first is False!\", ] err = \", \".join(err) err", "self._last_result = page_result # this should catch errors where API returns result data", "time from collections import OrderedDict from . import exceptions from .. import utils", "m = \"Mapped parameter {k!r}='{v}' for {s}\" m = m.format(k=key, v=value, s=sensor) self.log.debug(m)", "print_function from __future__ import unicode_literals import datetime import json import time from collections", "get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0", "pct of clients total instead of until question expiration. Defaults to: 0. poll_total", "True: if len(all_rows or []) >= data.row_count: m = \"Received expected row_count {c},", "returns dict. Otherwise, return str. \"\"\" self._check_id() client_args = {} client_args.update(kwargs) client_args[\"method\"] =", "= export_id m = [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ]", "allow_undefined (:obj:`bool`, optional): Allow parameter keys that are not in the parameters definition", "value, operator=\"regex\", ignore_case_flag=True, not_flag=False, all_values_flag=False, max_age_seconds=0, type=None, ): \"\"\"Set a filter for this", "result and ask it. Args: index (:obj:`int`, optional): Index of parse result to", "ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result = self.adapter.cmd_get(obj=self.obj) self._last_result = result", "optional): Operator to use for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to:", "CEF format\", \"export_id={e!r}\"] m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id", "{status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow()", "if not sensor.parameter_definition: m = \"No parameters defined on sensor {s}, going to", "a page returns no answers or the expected row count is hit. Returns:", "[\"Received Server Side Export start response for XML format\", \"code={c}\"] m = \",", "= self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ):", "clients at a time from the API. If 0, disables paging and gets", "``obj`` was generated from. Defaults to: None. \"\"\" self._lvl = lvl self.log =", "page. Defaults to: 2. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs:", "on value. Defaults to: True. not_flag (:obj:`bool`, optional): If set, negate the match.", "value is not set, \"\", or None, throw an exception. Defaults to: True.", "of the question. Args: sensor (:obj:`Sensor`): Sensor workflow object. set_param_defaults (:obj:`bool`, optional): If", "+ \"Y|MO|W|D|H|M|S\" units) \"TimeDiff\": 7, # e.g. 125MB or 23K or 34.2Gig (numeric", "by seeing if self.obj.id is set.\"\"\" if not self.obj.id: m = \"No id", "True have the API return all rows that do not match the operator.", "\"\"\"Return any parse result that is an exact match.\"\"\" for x in self.obj:", "end - start m = \"Finished getting {rows} answers in {dt}\" m =", "= m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params select.sensor.source_id =", "ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt = now_dt + ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter =", "\"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator in OPERATOR_MAP: return OPERATOR_MAP[operator]", "0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1 m", "m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status", "= any([x.question.from_canonical_text for x in result_obj]) m = \"Received {n} parse results (any", "to: \"last_registration\". page_size (:obj:`int`, optional): Get N number of clients at a time", "= result m = [\"Received Server Side Export start response for CSV format\",", "sensor_id][0] if not sensor.parameter_definition: m = \"No parameters defined on sensor {s}, going", "Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format atmpl = \"{k}='{v}'\".format attrs = [\"id\", \"query_text\"]", "= cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas =", "(:obj:`int`, optional): If True have the API return all rows that do not", "lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of kwargs: Passed", "Defaults to: 5. poll_pct (:obj:`int`, optional): Wait until the percentage of clients total", "Defaults to: \"last_registration\". page_size (:obj:`int`, optional): Get N number of clients at a", "every N seconds. Defaults to: 5. max_poll_count (:obj:`int`, optional): If not 0, only", "sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self, \"_filter\"): self._filter =", "answers for this question in XML format using server side export. Args: export_id", "paging_result = adapter.cmd_get(**paging_get_args) log.debug(result.pretty_bodies()) paging_result_obj = paging_result() page_rows = len(paging_result_obj) received_rows += page_rows", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args =", "elif pvals: derived_default = pvals[0] else: derived_default = \"\" p[\"derived_default\"] = derived_default return", "self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas = datas data = datas[0]", "build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter select.sensor = self.api_objects.Sensor() for", "ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits", "pq.question.selects or [] for select in selects: if not param_values: m = \"No", "Side Export completed\", \"reached max poll count {c}\", \"status {status}\", ] m =", "= m.format(k=key, v=value, s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups or", "answers, considering all answers received\" self.log.info(m) break if max_page_count and page_count >= max_page_count:", "to: \"info\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_parse_question`. Returns: :obj:`ParsedQuestion` \"\"\" log", "= m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate type against :data:`TYPE_MAP`.\"\"\" if type", "result m = [\"Received Server Side Export start response for CEF format\", \"code={c}\"]", "Only return clients that have registered in N number of seconds. Defaults to:", "default value from each parameters definition. Defaults to: True. allow_empty_params (:obj:`bool`, optional): If", "get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size if", "poll_count = 0 while True: poll_count += 1 m = \"New polling loop", "to set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default value from parameter", "for this sensor. Notes: Will try to resolve a default value and store", "to: False. return_obj (:obj:`bool`, optional): If export_id is XML format, return a ResultSet", "= leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result", "len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id =", "in enumerate(self.obj): pq_txt = pq_tmpl( idx=idx, text=pq.question_text, params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt)", "is_ex if is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt -", "been asked (id is set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then", "= getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] = cache_id page_count = 1 m = \"Received", "def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value", "): \"\"\"Set a filter for this sensor to be used in a question.", "for XML format and get an export_id. Args: hashes (:obj:`bool`, optional): Have the", "left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key, value=value))", "against the value in last_reg. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"greaterequal\".", "match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP", "params = param_defs.get(\"parameters\", []) for p in params: pdef = p.get(\"defaultValue\", \"\") pval", "pick and ask it. Defaults to: True. use_first (:obj:`bool`, optional): If index is", "Passed to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for", "True. \"\"\" param_def = self.params_defined.get(key, None) if param_def is None: m = \"Parameter", "to each line. Defaults to: \"\". **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`.", "cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] = page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"]", "self._last_result = result m = [\"Received Server Side Export start response for CSV", "the max age property of the sensor. Defaults to: 0. all_values_flag (:obj:`bool`, optional):", "\", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True,", "is set, try to derive the default value from each parameters definition. Defaults", "cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result datas = result() self._last_datas", "self.map_group_params(pq, sub_group) @property def result_indexes(self): \"\"\"Get the parse result indices in str form.\"\"\"", "= self.get_canonical m = \"Picking parsed question based on exact match: {pq.question}\" m", "parameters defined, and the value is not set, \"\", or None, throw an", "can be before we consider it invalid. 0 means to use the max", "\"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"name={!r}\".format(self.obj.name), \"filter={}\".format(\", \".join(self.filter_vals)), ] if self.params_defined", "kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args = {} client_args.update(kwargs) client_args[\"method\"] =", "{p.key!r} value {p.value!r} is empty, definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise", "for each parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\")", "infos[0] est_total = info.estimated_total poll_total = est_total if poll_total and poll_total <= est_total:", "out of {pct}\", \"{info.mr_passed} out of {this_total}\", \"estimated_total: {info.estimated_total}\", \"poll count: {c}\", ]", "self._last_datas = datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False,", "API keep the cache_id that is created on initial get answers page alive", "= page_datas page_data = page_datas[0] page_rows = page_data.rows m = \"Received page #{c}", "def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side export for CEF", "a server side export for completion. Args: export_id (:obj:`str`): An export id returned", "= utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct} out of {pct}\", \"{info.mr_passed}", "N retries if that happens page_datas = page_result() self._last_datas = page_datas page_data =", "(:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to: 5. **kwargs:", "\"{k}='{v}'\".format attrs = [\"id\", \"query_text\"] bits = [atmpl(k=attr, v=getattr(self.obj, attr, None)) for attr", "first matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else: err = [", "result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\",", ":data:`OPERATOR_MAP`. Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have the API return", "returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus", "pval not in [\"\", None]: derived_default = pval elif pvals: derived_default = pvals[0]", "to parse. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". **kwargs: rest of", "selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m =", "Side Export completed: {status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\":", "m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >= max_poll_count: m =", "m = \"No parameters defined on sensor {s}, going to next\" m =", "\".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self): \"\"\"Return any parse", "x in group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition: m = \"No", "m = \"No id issued yet, ask the question!\" raise exceptions.ModuleError(m) @property def", "be set. Throws exception if False and key not in :attr:`Sensor.param_keys`. Defaults to:", "export_id def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this questions server side", "level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(), adapter=adapter, lvl=lvl) @classmethod def", "polling loop #{c} for {o}\" m = m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >=", "\"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\") if x.strip()]", "est_total if poll_total and poll_total <= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed,", "break if self.expiration[\"expired\"]: m = \"Reached expiration {expiration}, considering all answers in\" m", "m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total)", "exact match: {em}\".format(em=True if self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits)) cls", "cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns:", "def answers_sse_get_status(self, export_id, **kwargs): \"\"\"Get the status for this questions server side export.", "sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if", "None and one of the parse results is an exact match, pick and", "text, lvl=\"info\", **kwargs): \"\"\"Get parse results of text from API. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "= self.filter select.sensor = self.api_objects.Sensor() for key in self.params_defined: if key not in", "= json.loads(self.obj.parameter_definition or \"{}\") params = param_defs.get(\"parameters\", []) for p in params: pdef", "type against :data:`TYPE_MAP`.\"\"\" if type in TYPE_MAP: return TYPE_MAP[type] m = \"Type {o!r}", "p in self.params: ret[p.key] = p.value return ret @property def params(self): \"\"\"Get the", "for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def __str__(self): \"\"\"Show", "= \"Reached stop_dt {stop_dt}, considering all answers in\" m = m.format(stop_dt=stop_dt) self.log.info(m) break", "workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. lvl (:obj:`str`, optional):", "ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch this", "considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count += 1 page_result =", "headers=True, hashes=False, **kwargs ): \"\"\"Start up a server side export for CSV format", "{status}\" m = m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False,", "return m = \"Now mapping parameters for group filter: {gf}\" m = m.format(gf=group_filter)", "m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >= max_poll_count: m = \"Reached max", "export_id m = [ \"Received SSE status response: path={r.request.url!r}\", \"code={r.status_code}\", \"status={status}\", ] m", "\"rows in answers: {info.row_count}\", \"poll count: {c}\", ] m = \", \".join(m) m", "to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args", "Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed question: {w}\" m", "values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", "(:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Question(id=id))", "return_obj=True, **kwargs ): \"\"\"Get the answers for this question in XML format using", "(:obj:`int`, optional): Size of each page to fetch at a time. Defaults to:", "18 days, 4 hours, 22 minutes: # 'TimeDiff', and 3.67 seconds\" or \"4.2", "name when sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`, optional): Allow parameter", "to put before and after parameter key name when sending to API. Defaults", "If export_id is XML format, return a ResultSet object. Defaults to: True. **kwargs:", "page alive for N seconds. Defaults to: 900. hashes (:obj:`bool`, optional): Have the", "of filters to be used in :meth:`Clients.get_all. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use", "= page_size if filters is not None: get_args[\"cache_filters\"] = filters if page_size: get_args[\"row_start\"]", "there is no exact match, pick the first parse result and ask it.", "op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag", "= datetime.datetime.utcnow() elapsed = end - start m = \"Finished getting answers in", "= export_id status = self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count and", "completed: {status}\" m = m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m =", "filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get all Clients as", "None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator =", "(:obj:`str`, optional): String to put before and after parameter key name when sending", "select.sensor if not sensor.parameter_definition: m = \"No parameters defined on sensor {s}, going", "already been asked (id is set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"],", "param in self.params: if param.value in [\"\", None] and not allow_empty_params: m =", "a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this", "param in params: if not param_values: m = \"No more parameter values left", "for this sensor to be set. Throws exception if False and key not", "whole=this_total) poll_count = 0 while True: poll_count += 1 m = \"New polling", "= \"Picking parsed question based on index {index}: {pq.question}\" m = m.format(index=index, pq=pq)", "the answers for this question. Args: hashes (:obj:`bool`, optional): Have the API include", "Defaults to: 99. poll_secs (:obj:`int`, optional): If not 0, wait until N seconds", "dt=elapsed) self.log.info(m) return datas def answers_sse_start_xml(self, hashes=False, **kwargs): \"\"\"Start up a server side", "received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0)", "m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield obj if page_size: paging_get_args =", "answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos = self.answers_get_info(**kwargs) info = infos[0]", "Clients(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits", "def answers_get_info(self, **kwargs): \"\"\"Return the ResultInfo for this question. Args: **kwargs: rest of", "{} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count =", "self.log.info(m) page_count += 1 page_result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should", "poll_total = est_total if poll_total and poll_total <= est_total: this_total = poll_total now_pct", "workflow. name (:obj:`str`): Name of sensor to fetch. lvl (:obj:`str`, optional): Logging level.", "\"Received a page with no answers, considering all answers received\" self.log.info(m) break if", "m = \", \".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m =", "sensor_id = group_filter.sensor.id sensor = [x for x in group_sensors if x.id ==", "param_values = pq.parameter_values selects = pq.question.selects or [] for select in selects: if", "cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\":", "= m.format(dt=elapsed) self.log.info(m) datas = result() self._last_datas = datas return datas def answers_get_data_paged(", "self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag = all_values_flag self.filter.max_age_seconds", "self.log.info(m) time.sleep(poll_sleep) end = datetime.datetime.utcnow() elapsed = end - start m = [", "self, key, value=\"\", derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for this", ":obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs)", "if received_rows >= total_rows: m = \"Reached total rows count {c}, considering all", "values left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value = param_values.pop(0) sensor.parameters.append(param_cls(key=key,", "[\"\", None] and not allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is empty,", "total instead of ``estimated_total`` of clients from API. Defaults to: 0. max_poll_count (:obj:`int`,", "adapter, name, lvl=\"info\"): \"\"\"Get a sensor object by name. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter", "page_count >= max_page_count: m = \"Reached max page count {c}, considering all answers", "@property def expiration(self): \"\"\"Get expiration details for this question. Returns: :obj:`dict` \"\"\" now_dt", "in self.obj: if x.question.from_canonical_text: return x return None def map_select_params(self, pq): \"\"\"Map parameters", "m = \"Picking first matching parsed question: {pq.question}\" m = m.format(pq=pq) self.log.info(m) else:", "Defaults to: True. not_flag (:obj:`bool`, optional): If set, negate the match. Defaults to:", "\"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"},", "of a ClientStatus object to have API sort the return on. Defaults to:", "self.params_defined.get(key, None) if param_def is None: m = \"Parameter key {o!r} is not", "ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\",", "m = \"Reached max page count {c}, considering all clients fetched\" m =", "answers will be returned in one API response. For large data sets of", "trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m = [\"Received", "API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args = {}", "\"\"\"Poll a server side export for completion. Args: export_id (:obj:`str`): An export id", "m.format(now_pct=PCT_FMT(now_pct), pct=PCT_FMT(poll_pct)) self.log.info(m) break if datetime.datetime.utcnow() >= stop_dt: m = \"Reached stop_dt {stop_dt},", "None: m = \"No parse results returned for text: {t!r}\" m = m.format(t=text)", "set), we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if", "If max_page_count and max_row_count are 0, fetch pages until a page returns no", "be appended to it. If this is None, a new CacheFilterList will be", "= adapter.api_objects.SystemStatusList() for client_obj in cls.get_all_iter(adapter=adapter, **kwargs): obj.append(client_obj) return obj class Sensor(Workflow): def", "m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for XML format\",", "If index is None and there is no exact match, pick the first", "-*- coding: utf-8 -*- \"\"\"Workflow encapsulation package for performing actions using the Tanium", "client_args[\"path\"] = \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE", "infos m = \"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m) self.log.debug(format(self)) return", "self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\") if x.strip()] status = dict(zip([\"status\",", "value. operator (:obj:`str`, optional): Operator to use for filter_value. Must be one of", "result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV format\", \"export_id={e!r}\"] m = \",", "this text to each line. Defaults to: \"\". trailing (:obj:`str`, optional): Append this", "ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch this question.\"\"\" self._check_id() result =", "\"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod", "m.format(c=poll_count, o=self) self.log.debug(m) if now_pct >= poll_pct: m = \"Reached {now_pct} out of", "max_poll_count: m = \"Reached max poll count {c}, considering all answers in\" m", "{rows} answers in {dt}\" m = m.format(rows=len(all_rows or []), dt=elapsed) self.log.info(m) return datas", "): \"\"\"Poll for answers from clients for this question. Args: poll_sleep (:obj:`int`, optional):", "key value pairs of the filter for this sensor. Returns: :obj:`list` of :obj:`str`", "self.answers_sse_get_status(**sse_args) while True: poll_count += 1 if max_poll_count and poll_count >= max_poll_count: m", "not param_values: m = \"No more parameter values left to map\" self.log.debug(m) return", "result = adapter.cmd_parse_question(**cmd_args) result_obj = result() if result_obj is None: m = \"No", "page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m = m.format( page_rows=page_rows, received_rows=received_rows,", "self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for XML format\", \"export_id={e!r}\"]", "to this many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional): Have the API", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", "self.get_canonical else False), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls,", "of each client status is compared against the value in last_reg. Must be", "return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter( adapter, last_reg=300, operator=\"greaterequal\", not_flag=False, filters=None ): \"\"\"Build", "total is N percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If not 0,", "division from __future__ import print_function from __future__ import unicode_literals import datetime import json", "count {c}, considering all answers in\" m = m.format(c=max_poll_count) self.log.info(m) break infos =", "for this sensor. Returns: :obj:`tantrum.api_objects.ApiObjects`: ParameterList API object \"\"\" if not hasattr(self, \"_params\"):", "Only fetch up to this many rows. Defaults to: 0. cache_expiration (:obj:`int`, optional):", "count {c}, considering all answers in\" m = m.format(c=max_page_count) self.log.info(m) break if max_row_count", "or :obj:`str`: If return_obj = True returns ResultSetList ApiModel object. If return_dict =", "= self.obj.id else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return select class Question(Workflow):", "est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count = 0 while True:", "not one of the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined:", "for x in group_sensors if x.id == sensor_id][0] if not sensor.parameter_definition: m =", "optional): When page_size is not 0, have the API keep the cache of", "= { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\":", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading:", "ret[p.key] = p.value return ret @property def params(self): \"\"\"Get the parameters that are", ":obj:`ParsedQuestion` \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) cmd_args = {} cmd_args.update(kwargs) cmd_args[\"text\"] = text", "utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args = {} get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start", "optional): Size of each page to fetch at a time. Defaults to: 1000.", "\"Server Side Export completed\", \"reached max poll count {c}\", \"status {status}\", ] m", "to fetch at a time. Defaults to: 1000. max_page_count (:obj:`int`, optional): Only fetch", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt = start", "expiration {expiration}, considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count", "cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"export_flag\"] = True cmd_args[\"export_format\"] = 2 if leading: cmd_args[\"export_leading_text\"]", "\"\"\"Set a filter for this sensor to be used in a question. Args:", "of the parse results is an exact match, pick and ask it. Defaults", "{} client_args.update(kwargs) client_args[\"method\"] = \"get\" client_args[\"path\"] = \"export/{export_id}.status\".format(export_id=export_id) client_args[\"data\"] = \"\" r =", "to: 1000. max_page_count (:obj:`int`, optional): Only fetch up to this many pages. If", "\"Less\", \"tmpl\": \"{value}\"}, \"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"},", "method=r.request.method, url=r.request.url, status_code=r.status_code, origin=r, lvl=self.log.level, ) data = \"<{r}>{data}</{r}>\".format(data=data, r=\"result_set\") src = \"SSE", "= self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end =", "parsed question based on exact match: {pq.question}\" m = m.format(pq=pq) self.log.info(m) elif use_first:", "cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args)", "= adapter.cmd_get(obj=adapter.api_objects.Sensor(name=name)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"):", "page count {c}, considering all answers in\" m = m.format(c=max_page_count) self.log.info(m) break if", "the API include the hashes of rows values Defaults to: False. **kwargs: rest", "is None: m = \"No parse results returned for text: {t!r}\" m =", "get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a question object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq =", "for this question. Args: hashes (:obj:`bool`, optional): Have the API include the hashes", "of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\" self._check_id() cmd_args", "Adapter to use for this workflow. name (:obj:`str`): Name of sensor to fetch.", "it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow()", "to :meth:`tantrum.adapter.Adapter.cmd_get`. Yields: :obj:`tantrum.api_objects.ApiObjects`: ClientStatus API object \"\"\" log = utils.logs.get_obj_log(obj=cls, lvl=lvl) get_args", "{d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters = self.params", "for answers until for {o} until {stop_dt}\" m = m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos", "= None sensor.parameters = self.api_objects.ParameterList() params = json.loads(sensor.parameter_definition)[\"parameters\"] for param in params: if", "\"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\", \"tmpl\": \"{value}\"}, \"equal\": {\"op\": \"Equal\", \"tmpl\": \"{value}\"}, \"regex\": {\"op\":", "delim (:obj:`str`, optional): String to put before and after parameter key name when", "hashes of rows values. Defaults to: False. **kwargs: rest of kwargs: Passed to", "\"\"\"Get the answers for this question one page at a time. Args: page_size", "if \"xml\" in export_id and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects, response_body=r.text,", "= \"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE data", "\"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter( self, key, value=\"\", derive_default=True, delim=\"||\",", "= pq.parameter_values selects = pq.question.selects or [] for select in selects: if not", "else: select.sensor.hash = self.obj.hash select.WORKFLOW = self return select class Question(Workflow): def __str__(self):", "= \"Type {o!r} is invalid, must be one of {vo}\" m = m.format(o=type,", "(:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. last_reg (:obj:`int`, optional): Only return clients", "datetime.timedelta(seconds=poll_secs) else: stop_dt = self.expiration[\"expiration\"] m = \"Start polling loop for answers until", "= page_size cmd_args[\"cache_expiration\"] = cache_expiration cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "\".join(err) err = [err, \"Supply an index of a parsed result:\", self.result_indexes] err", "optional): If index is None and there is no exact match, pick the", "to: None. \"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator", "info = infos[0] now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct}", "self.adapter = adapter self._result = result self._last_result = result def __repr__(self): \"\"\"Show object", "page length={len}, cache_info={cache!r}\" m = m.format(len=received_rows, cache=result_cache) log.info(m) for obj in result_obj: yield", "self.filter.value_type = type def build_select(self, set_param_defaults=True, allow_empty_params=False): select = self.api_objects.Select() select.filter = self.filter", "- ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return ret def refetch(self): \"\"\"Re-fetch", "seconds for pct of clients total instead of until question expiration. Defaults to:", "+= 1 m = \"New polling loop #{c} for {o}\" m = m.format(c=poll_count,", "an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows if possible (single line", "return data return data class ParsedQuestion(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`)", "text (:obj:`str`): Question text to parse. lvl (:obj:`str`, optional): Logging level. Defaults to:", "lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @property def get_canonical(self):", "to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: This will not", "s=sensor) self.log.debug(m) group_filter.sensor = sensor for sub_group in group.sub_groups or []: self.map_group_params(pq, sub_group)", "sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to: 5.", "a default value and store it in \"derived_default\" key for each parameter definition", ") filters = filters or adapter.api_objects.CacheFilterList() filters.append(cfilter) return filters @classmethod def get_all_iter( cls,", "registered in N number of seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines", "): \"\"\"Build a set of filters to be used in :meth:`Clients.get_all. Args: adapter", "from :meth:`sse_start`. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapters.ApiClient`. Returns: :obj:`dict`: \"\"\" client_args", "def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits =", "get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for", "datetime import json import time from collections import OrderedDict from . import exceptions", "Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow. **kwargs: rest of kwargs:", "obj=result(), lvl=lvl, result=result) @classmethod def get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object", "parameter to set. Defaults to: \"\". derive_default (:obj:`bool`, optional): Get default value from", "if flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"] =", "elif use_exact_match and self.get_canonical: pq = self.get_canonical m = \"Picking parsed question based", "not self.obj.id: m = \"No id issued yet, ask the question!\" raise exceptions.ModuleError(m)", "= info.estimated_total poll_total = est_total if poll_total and poll_total <= est_total: this_total =", "leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up a server side export for CEF format and", "err = [ \"No index supplied\", \"no exact matching parsed result\", \"and use_first", "\"tmpl\": \"{value}\"}, } TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, #", "being the only item in it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict", "= \"Reached expiration {expiration}, considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break", "use_first: pq = self.obj[0] m = \"Picking first matching parsed question: {pq.question}\" m", "\"DataSize\": 8, \"NumericInteger\": 9, \"VariousDate\": 10, \"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT =", "= m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and poll_count >= max_poll_count: m = \"Reached", "if self.obj.id is set.\"\"\" if not self.obj.id: m = \"No id issued yet,", "poll_total and poll_total <= est_total: this_total = poll_total now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) poll_count", "and set_param_defaults: self.set_parameter(key=key, derive_default=True) for param in self.params: if param.value in [\"\", None]", "{e!r}\"] m = \", \".join(m) m = m.format(r=r, e=export_id) self.log.info(m) data = r.text", "self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"] self.filter.ignore_case_flag = ignore_case_flag self.filter.not_flag = not_flag self.filter.all_values_flag", "lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns: :obj:`Question` \"\"\" return cls(obj=adapter.api_objects.Question(),", "m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_cef(self, leading=\"\", trailing=\"\", **kwargs): \"\"\"Start up", "will be created with the last_registration filter being the only item in it.", "optional): If not 0, wait until N seconds for pct of clients total", "\"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @classmethod def new(cls, adapter,", "is_ex: ret[\"expire_ago\"] = now_dt - ex_dt else: ret[\"expire_in\"] = ex_dt - now_dt return", "of until question expiration. Defaults to: 0. poll_total (:obj:`int`, optional): If not 0,", "parameter definition returned. Returns: :obj:`collections.OrderedDict` \"\"\" param_defs = json.loads(self.obj.parameter_definition or \"{}\") params =", "to: True. hashes (:obj:`bool`, optional): Have the API include the hashes of rows", "filter for this sensor to be used in a question. Args: value (:obj:`str`):", ":obj:`object`: ResultInfoList API object \"\"\" # TODO: Add wait till error_count / no_results_count", "self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the key value pairs of the", "lvl self.log = utils.logs.get_obj_log(obj=self, lvl=lvl) self.obj = obj self.adapter = adapter self._result =", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for this question one page", "Flatten CSV rows if possible (single line in each cell) Defaults to: False.", "question based on index {index}: {pq.question}\" m = m.format(index=index, pq=pq) self.log.info(m) elif use_exact_match", "= pq.question_group_sensors param_values = pq.parameter_values if not group: m = \"Empty group, not", "m = \"Reached total rows count {c}, considering all clients fetched\" m =", "hashes of rows values Defaults to: False. **kwargs: rest of kwargs: Passed to", "max pages of {max_row_count}, considering all answers received\" m = m.format(max_row_count=max_row_count) self.log.info(m) page_count", "page_size (:obj:`int`, optional): Get N number of clients at a time from the", "fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows >= total_rows: m = \"Reached", "of rows values Defaults to: False. **kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`.", "result=result ) m = \"Added parsed question: {w}\" m = m.format(w=workflow) self.log.info(m) workflow.refetch()", "left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m = \"Finished mapping parameters", "Returns: :obj:`tantrum.api_objects.ApiObjects`: Filter API object \"\"\" if not hasattr(self, \"_filter\"): self._filter = self.api_objects.Filter()", "of sensor to fetch. lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". Returns:", "(:obj:`object`, optional): Tantrum CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional):", "\"Server Side Export failed: {status}\" m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status =", "Defaults to: \"greaterequal\". not_flag (:obj:`int`, optional): If True have the API return all", "this sensor to be set. Throws exception if False and key not in", "include the hashes of rows values Defaults to: False. **kwargs: rest of kwargs:", "(any exact match: {ac})\" m = m.format(n=len(result_obj), ac=any_canonical) log.info(m) return cls(adapter=adapter, obj=result_obj, lvl=lvl,", "param_cls = self.api_objects.Parameter group_sensors = pq.question_group_sensors param_values = pq.parameter_values if not group: m", "be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys())) raise exceptions.ModuleError(m) def get_type_map(type): \"\"\"Validate", "s=sensor) self.log.debug(m) def map_group_params(self, pq, group): \"\"\"Map parameters to filters on the right", "optional): Check for answers every N seconds. Defaults to: 5. poll_pct (:obj:`int`, optional):", "if leading: cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args)", "= {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj start = datetime.datetime.utcnow() if poll_secs: stop_dt =", "+= page_rows cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end -", "definitions for this sensor. Notes: Will try to resolve a default value and", "m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CSV format\",", "in N number of seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines how", "cmd_args[\"export_leading_text\"] = leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result =", "for p in self.params: ret[p.key] = p.value return ret @property def params(self): \"\"\"Get", "left to map\" self.log.debug(m) return sensor = select.sensor if not sensor.parameter_definition: m =", "default value and store it in \"derived_default\" key for each parameter definition returned.", "values left to map\" self.log.debug(m) return m = \"Now mapping parameters for group", "return obj class Sensor(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" ctmpl", "\"Parameter key {o!r} is not one of the defined parameters {ov}\" m =", "(:obj:`int`, optional): Have the API keep the cache_id that is created on initial", "CacheFilterList returned from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of a", "[ \"Received page_rows={page_rows}\", \"received_rows={received_rows}\", \"total_rows={total_rows}\", ] m = \", \".join(m) m = m.format(", "m.format(c=max_page_count) self.log.info(m) break if max_row_count and len(all_rows or []) >= max_row_count: m =", "allow_empty_params: m = \"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\" m =", "self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF format\", \"export_id={e!r}\"]", "m = \", \".join(m) m = m.format(r=r, status=status) self.log.debug(m) return status def answers_sse_poll(self,", "question!\" raise exceptions.ModuleError(m) @property def expiration(self): \"\"\"Get expiration details for this question. Returns:", "for selects, parameter values left: {pv!r}\" m = m.format(pv=pq.parameter_values) self.log.debug(m) self.map_group_params(pq=pq, group=pq.question.group) m", "percentage of clients total is N percent. Defaults to: 99. poll_secs (:obj:`int`, optional):", "get_by_id(cls, adapter, id, lvl=\"info\"): \"\"\"Get a sensor object by id. Args: adapter (:obj:`tantrum.adapters.Adapter`):", "set_param_defaults=set_param_defaults, allow_empty_params=allow_empty_params ) if not getattr(self.obj, \"selects\", None): self.obj.selects = self.api_objects.SelectList() self.obj.selects.append(select) def", "= datas return datas def answers_get_data_paged( self, page_size=1000, max_page_count=0, max_row_count=0, cache_expiration=900, hashes=False, sleep=5,", "API returns result data as None sometimes # need to refetch data for", "errors where API returns result data as None sometimes # need to refetch", "m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\" in export_id and (return_dict or", ":meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Notes: If max_page_count and max_row_count are 0, fetch pages until a page", "params=list(pq.parameter_values or []), exact=bool(pq.question.from_canonical_text), ) pq_list.append(pq_txt) return \"\\n\".join(pq_list) def pick(self, index=None, use_exact_match=True, use_first=False,", "[ \"No index supplied\", \"no exact matching parsed result\", \"and use_first is False!\",", "to :meth:`Clients.get_all_iter`. Returns: :obj:`tantrum.api_objects.ApiObjects`: SystemStatusList API object \"\"\" obj = adapter.api_objects.SystemStatusList() for client_obj", "return infos def answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll", "keys] else: vals = [] return vals def set_filter( self, value, operator=\"regex\", ignore_case_flag=True,", "the parse results is an exact match, pick and ask it. Defaults to:", "4, # SENSOR_RESULT_TYPE_IPADDRESS \"IPAddress\": 5, # SENSOR_RESULT_TYPE_DATE_WMI \"WMIDate\": 6, # e.g. \"2 years,", "m = m.format(pq=pq) self.log.info(m) else: err = [ \"No index supplied\", \"no exact", "until N clients have total instead of ``estimated_total`` of clients from API. Defaults", "ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, ) filters = filters", "attr in attrs] bits += [atmpl(k=k, v=v) for k, v in self.expiration.items()] bits", "to: 0. poll_total (:obj:`int`, optional): If not 0, wait until N clients have", "max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients for this question. Args: poll_sleep", "Passed to :meth:`answers_sse_get_status`. Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0", "derive_default=True, delim=\"||\", allow_undefined=True ): \"\"\"Set a parameters value for this sensor. Args: key", "group.filters or []: if not param_values: m = \"No more parameter values left", "return cls(adapter=adapter, obj=result_obj, lvl=lvl, result=result) OPERATOR_MAP = { \"less\": {\"op\": \"Less\", \"tmpl\": \"{value}\"},", "= result.str_to_obj(text=data, src=src, try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data =", "result_obj = result() received_rows = len(result_obj) result_cache = getattr(result_obj, \"cache_info\", None) total_rows =", "format and get an export_id. Args: hashes (:obj:`bool`, optional): Have the API include", "to resolve a default value and store it in \"derived_default\" key for each", "def param_values(self): \"\"\"Get all of the parameter key and values. Returns: :obj:`OrderedDict` \"\"\"", "ret @property def params(self): \"\"\"Get the parameters that are set for this sensor.", "\"||\". allow_undefined (:obj:`bool`, optional): Allow parameter keys that are not in the parameters", "get_all_iter( cls, adapter, filters=None, sort_fields=\"last_registration\", page_size=1000, max_page_count=0, cache_expiration=600, sleep=2, lvl=\"info\", **kwargs ): \"\"\"Get", "the defined parameters {ov}\" m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise", "ago_td ago_str = ago_dt.strftime(adapter.api_objects.module_dt) cfilter = adapter.api_objects.CacheFilter( field=\"last_registration\", type=\"Date\", operator=op_dict[\"op\"], not_flag=not_flag, value=ago_str, )", "a sensor to the left hand side of the question. Args: sensor (:obj:`Sensor`):", "poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from clients for this question. Args:", "the key value pairs of the filter for this sensor. Returns: :obj:`list` of", "export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep", "self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"] m =", "cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question(", "param_defs.get(\"parameters\", []) for p in params: pdef = p.get(\"defaultValue\", \"\") pval = p.get(\"value\",", "is None and there is no exact match, pick the first parse result", "self.adapter.cmd_get_result_data(**cmd_args) self._last_result = page_result # this should catch errors where API returns result", "\", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def answers_get_data(self, hashes=False,", "m = m.format(r=r, e=export_id) self.log.info(m) data = r.text if \"xml\" in export_id and", "Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td = datetime.timedelta(seconds=-(int(last_reg))) ago_dt", "\"\"\" ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [ \"parse matches: {c}\".format(c=len(self.obj)), \"has exact match:", "{expiration}, considering all answers in\" m = m.format(expiration=self.expiration) self.log.info(m) break if max_poll_count and", "None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"] =", "max_row_count=0, cache_expiration=900, hashes=False, sleep=5, **kwargs ): \"\"\"Get the answers for this question one", "TYPE_MAP = { \"Hash\": 0, # SENSOR_RESULT_TYPE_STRING \"String\": 1, # SENSOR_RESULT_TYPE_VERSION \"Version\": 2,", "this sensor. Args: key (:obj:`str`): Key name of parameter to set. value (:obj:`str`,", "m.format(status=status) self.log.info(m) break if status[\"status\"] == \"failed\": m = \"Server Side Export failed:", "attrs] bits += [atmpl(k=k, v=v) for k, v in self.expiration.items()] bits = \"(\\n", "r.text if \"xml\" in export_id and (return_dict or return_obj): result = results.Soap( api_objects=self.api_objects,", "try_int=False) if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data", "{c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else False), ] bits = \"({})\".format(\",", "self.log.info(m) elif use_first: pq = self.obj[0] m = \"Picking first matching parsed question:", "[atmpl(k=k, v=v) for k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls", "\"RegexMatch\": 11, \"LastOperatorType\": 12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against", "cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj result = self.adapter.cmd_get_result_info(**cmd_args) self._last_result = result", "optional): If a CacheFilterList object is supplied, the last_registration filter generated by this", "hashes=False, **kwargs): \"\"\"Get the answers for this question. Args: hashes (:obj:`bool`, optional): Have", "= page_datas[0] page_rows = page_data.rows m = \"Received page #{c} answers: {rows}\" m", "client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\")", "0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] = self.obj cmd_args[\"row_start\"] = row_start cmd_args[\"row_count\"] =", "max_poll_count: m = [ \"Server Side Export completed\", \"reached max poll count {c}\",", "matches: {c}\".format(c=len(self.obj)), \"has exact match: {em}\".format(em=True if self.get_canonical else False), ] bits =", "Returns: :obj:`list` of :obj:`str` \"\"\" if any([self.filter.value, self.filter.operator]): keys = [ \"operator\", \"value\",", "cmd_args[\"row_start\"] += page_size time.sleep(sleep) end = datetime.datetime.utcnow() elapsed = end - start m", "params\" self.log.debug(m) return if not group_sensors: m = \"No question group sensors defined,", "\"No parse results returned for text: {t!r}\" m = m.format(t=text) raise exceptions.ModuleError(m) any_canonical", "m = \", \".join(m) m = m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self,", "flatten else 0 cmd_args[\"export_hide_csv_header_flag\"] = False if headers else True cmd_args[\"include_hashes_flag\"] = hashes", "**kwargs): \"\"\"Return the ResultInfo for this question. Args: **kwargs: rest of kwargs: Passed", "self._last_infos = infos m = \"Received answers info: {infos}\" m = m.format(infos=infos.serialize()) self.log.debug(m)", "m = m.format(o=key, ov=list(self.params_defined.keys())) if allow_undefined: self.log.info(m) else: raise exceptions.ModuleError(m) elif derive_default and", "self.log.info(m) else: err = [ \"No index supplied\", \"no exact matching parsed result\",", "and get an export_id. Args: flatten (:obj:`bool`, optional): Flatten CSV rows if possible", "\"lessequal\": {\"op\": \"LessEqual\", \"tmpl\": \"{value}\"}, \"greater\": {\"op\": \"Greater\", \"tmpl\": \"{value}\"}, \"greaterequal\": {\"op\": \"GreaterEqual\",", "how the last_registered attribute of each client status is compared against the value", "leading if trailing: cmd_args[\"export_trailing_text\"] = trailing result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result m", "{text!r}, params: {params}, exact: {exact}\" pq_tmpl = pq_tmpl.format pq_list = [] for idx,", "if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter( self, key,", "to: None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object to have API", "page_rows = page_data.rows m = \"Received page #{c} answers: {rows}\" m = m.format(c=page_count,", "r = self.adapter.api_client(**client_args) status_split = [x.strip().lower() for x in r.text.split(\".\") if x.strip()] status", "Clients as an iterator. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to use for this workflow.", "log.info(m) for obj in paging_result_obj: yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs):", "count {c}, considering all clients fetched\" m = m.format(c=max_page_count) log.info(m) break if received_rows", "answers received\" self.log.info(m) break if max_page_count and page_count >= max_page_count: m = \"Reached", "r = self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id: {e!r}\"]", "if return_dict: return data data = self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return", "bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls, bits=bits) @staticmethod def build_last_reg_filter(", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_info`. Returns: :obj:`tantrum.api_models.ApiModel`: ResultInfoList API Object \"\"\"", "yield obj time.sleep(sleep) @classmethod def get_all(cls, adapter, **kwargs): \"\"\"Get all Clients. Args: adapter", "if param.value in [\"\", None] and not allow_empty_params: m = \"Parameter {p.key!r} value", "we wipe out attrs: [\"id\", \"context_group\", \"management_rights_group\"], then add it. \"\"\" if self.obj.id:", "\"cache_info\", None) total_rows = getattr(result_cache, \"filtered_row_count\", 0) cache_id = getattr(result_cache, \"cache_id\", None) get_args[\"cache_id\"]", "self.log.info(m) elif use_exact_match and self.get_canonical: pq = self.get_canonical m = \"Picking parsed question", "An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional):", "ctmpl = \"{c.__module__}.{c.__name__}\".format bits = [\"count={}\".format(len(self.obj))] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__)", "answers_poll( self, poll_pct=99, poll_secs=0, poll_total=0, poll_sleep=5, max_poll_count=0, **kwargs ): \"\"\"Poll for answers from", "seconds. Defaults to: 300. operator (:obj:`str`, optional): Defines how the last_registered attribute of", "new(cls, adapter, lvl=\"info\"): \"\"\"Create a new Question workflow. Args: adapter (:obj:`tantrum.adapters.Adapter`): Adapter to", "(:obj:`bool`, optional): If sensor has parameters defined, and the value is not set,", "**kwargs ): \"\"\"Get the answers for this question in XML format using server", "Returns: :obj:`str`: \"\"\" self._check_id() start = datetime.datetime.utcnow() poll_count = 0 sse_args = {}", "= m.format(o=self, stop_dt=stop_dt) self.log.debug(m) infos = self.answers_get_info(**kwargs) info = infos[0] est_total = info.estimated_total", "export for CSV format and get an export_id. Args: flatten (:obj:`bool`, optional): Flatten", "\"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE data response\", \"code: {r.status_code}\", \"export_id:", "= self.api_objects.ResultSet(**data[\"result_set\"]) data = self.api_objects.ResultSetList(*[data]) return data return data class ParsedQuestion(Workflow): def __str__(self):", "self._last_result = result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`) \"\"\" return self.__str__()", "more parameter values left to map\" self.log.debug(m) return key = \"||{}||\".format(param[\"key\"]) value =", "operator in OPERATOR_MAP: return OPERATOR_MAP[operator] m = \"Operator {o!r} is invalid, must be", "get_args.update(kwargs) get_args[\"cache_sort_fields\"] = sort_fields get_args[\"obj\"] = adapter.api_objects.ClientStatus() row_start = 0 row_count = page_size", "definition for this sensor to be set. Throws exception if False and key", "\"\"\" op_dict = get_operator_map(operator) if type: get_type_map(type) self.filter.value = op_dict[\"tmpl\"].format(value=value) self.filter.operator = op_dict[\"op\"]", "m.format(e=export_id) self.log.info(m) return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start", "result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property def params_defined(self): \"\"\"Get the", "600. sleep (:obj:`int`, optional): Wait N seconds between fetching each page. Defaults to:", "this workflow. id (:obj:`int`): id of question to fetch. lvl (:obj:`str`, optional): Logging", "Notes: If export_id is not XML format or return_dict and return_obj False, return", "result\", \"and use_first is False!\", ] err = \", \".join(err) err = [err,", "paging and gets all clients in one call. Defaults to: 1000. max_page_count (:obj:`int`,", "Returns: :obj:`tantrum.api_models.ApiModel`: ResultDataList API Object \"\"\" self._check_id() start = datetime.datetime.utcnow() cmd_args = {}", "= [ \"Server Side Export completed\", \"reached max poll count {c}\", \"status {status}\",", "= m.format(dt=elapsed, status=status) self.log.info(m) return status def answers_sse_get_data( self, export_id, return_dict=False, return_obj=True, **kwargs", "{} cmd_args.update(kwargs) cmd_args[\"obj\"] = pq result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow =", "self.log.info(m) break if status[\"status\"] == \"completed\": m = \"Server Side Export completed: {status}\"", "many pages. If 0, get all pages. Defaults to: 0. cache_expiration (:obj:`int`, optional):", "export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side for CEF format\", \"export_id={e!r}\"] m", "to refetch data for N retries if that happens page_datas = page_result() self._last_datas", "is invalid, must be one of {vo}\" m = m.format(o=type, vo=list(TYPE_MAP.keys())) raise exceptions.ModuleError(m)", "on sensor {s}, going to next\" m = m.format(s=sensor) self.log.debug(m) continue sensor.source_id =", "page_rows: m = \"Received a page with no answers, considering all answers received\"", "return export_id def answers_sse_start_csv( self, flatten=False, headers=True, hashes=False, **kwargs ): \"\"\"Start up a", "\"\"\"Map parameters to filters on the right hand side of the question.\"\"\" param_cls", "\"no exact matching parsed result\", \"and use_first is False!\", ] err = \",", "many pages. If 0, get all pages. Defaults to: 0. max_row_count (:obj:`int`, optional):", "(:obj:`bool`, optional): If set, negate the match. Defaults to: False. max_age_seconds (:obj:`int`, optional):", "result = self.adapter.cmd_add_parsed_question(**cmd_args) result_obj = result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result", "k, v in self.expiration.items()] bits = \"(\\n {},\\n)\".format(\",\\n \".join(bits)) cls = ctmpl(c=self.__class__) return", "\".join(m) m = m.format(c=result.status_code) self.log.debug(m) export_id = result.object_obj[\"export_id\"] m = [\"Started Server Side", "False. headers (:obj:`bool`, optional): Include column headers. Defaults to: True. hashes (:obj:`bool`, optional):", "to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt = datetime.datetime.utcnow() ago_td =", "and len(all_rows or []) >= max_row_count: m = \"Hit max pages of {max_row_count},", "Args: export_id (:obj:`str`): An export id returned from :meth:`answers_sse_start_xml` or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`.", "\"estimated total clients: {d.estimated_total}\", ] m = \", \".join(m) m = m.format(d=data) self.log.info(m)", "now_pct = utils.tools.calc_percent(part=info.mr_passed, whole=this_total) m = [ \"Answers in {now_pct} out of {pct}\",", "when filtering on value. Defaults to: True. not_flag (:obj:`bool`, optional): If set, negate", "or :meth:`answers_sse_start_csv` or :meth:`answers_sse_start_cef`. poll_sleep (:obj:`int`, optional): Check for answers every N seconds.", "**kwargs: rest of kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_get_result_data`. Returns: :obj:`str`: \"\"\" cmd_args = {}", "\"info\". Returns: :obj:`Sensor` \"\"\" result = adapter.cmd_get(obj=adapter.api_objects.Sensor(id=id)) return cls(adapter=adapter, obj=result(), lvl=lvl, result=result) @property", "Server Side Export start response for CEF format\", \"code={c}\"] m = \", \".join(m)", "\"Finished polling for Server Side Export in {dt}, {status}\" m = m.format(dt=elapsed, status=status)", "result() workflow = Question( adapter=self.adapter, obj=result_obj, lvl=self.log.level, result=result ) m = \"Added parsed", "after parameter key name when sending to API. Defaults to: \"||\". allow_undefined (:obj:`bool`,", "to: 0. cache_expiration (:obj:`int`, optional): When page_size is not 0, have the API", "[\"\", None]: derived_default = pdef elif pval not in [\"\", None]: derived_default =", "import utils from .. import results class Workflow(object): def __init__(self, adapter, obj, lvl=\"info\",", "[ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits)) cls = ctmpl(c=self.__class__) return \"{cls}{bits}\".format(cls=cls,", "side export for CEF format and get an export_id. Args: leading (:obj:`str`, optional):", "definition: {d}\" m = m.format(p=param, d=self.params_defined.get(key, None)) raise exceptions.ModuleError(m) if self.params: select.sensor.parameters =", "self._check_id() start = datetime.datetime.utcnow() row_start = 0 cmd_args = {} cmd_args.update(kwargs) cmd_args[\"obj\"] =", "the cache of clients for this many seconds before expiring the cache. Defaults", "False, return the raw text as is. Returns: :obj:`tantrum.api_models.ApiModel` or :obj:`dict` or :obj:`str`:", "object \"\"\" if not hasattr(self, \"_params\"): self._params = self.api_objects.ParameterList() return self._params def set_parameter(", "= group_filter.sensor.id sensor = [x for x in group_sensors if x.id == sensor_id][0]", "self._filter.sensor.hash = self.obj.hash return self._filter @property def filter_vals(self): \"\"\"Get the key value pairs", "self.params_defined or self.param_values: bits += [ \"params_defined={}\".format(list(self.params_defined.keys())), \"param_values={}\".format(list(self.param_values.items())), ] bits = \"({})\".format(\", \".join(bits))", "to: 0. all_values_flag (:obj:`bool`, optional): Have filter match all values instead of any", "to use for filter_value. Must be one of :data:`OPERATOR_MAP`. Defaults to: \"regex\". ignore_case_flag", "= result m = [\"Received Server Side Export start response for XML format\",", "this. Must be one of :data:`TYPE_MAP` Defaults to: None. \"\"\" op_dict = get_operator_map(operator)", "{c}, considering all answers received\" m = m.format(c=data.row_count) self.log.info(m) break if not page_rows:", "False!\", ] err = \", \".join(err) err = [err, \"Supply an index of", "import absolute_import from __future__ import division from __future__ import print_function from __future__ import", "parsed result:\", self.result_indexes] err = \"\\n\".join(err) raise exceptions.ModuleError(err) self.map_select_params(pq=pq) m = \"Finished mapping", "in it. Defaults to: None. Returns: :obj:`Clients` \"\"\" op_dict = get_operator_map(operator) now_dt =", "\"status {status}\", ] m = \", \".join(m) m = m.format(c=max_poll_count, status=status) self.log.info(m) break", "12, } PCT_FMT = \"{0:.0f}%\".format def get_operator_map(operator): \"\"\"Validate operator against :data:`OPERATOR_MAP`.\"\"\" if operator", "\"tmpl\": \"{value}\"}, \"startswith\": {\"op\": \"RegexMatch\", \"tmpl\": \".*{value}\"}, \"endswith\": {\"op\": \"RegexMatch\", \"tmpl\": \"{value}.*\"}, \"contains\":", "lvl (:obj:`str`, optional): Logging level. Defaults to: \"info\". result (:obj:`tantrum.results.Result`, optional): Result object", "(:obj:`int`, optional): Check for answers every N seconds. Defaults to: 5. poll_pct (:obj:`int`,", "self.obj cmd_args[\"include_hashes_flag\"] = hashes result = self.adapter.cmd_get_result_data(**cmd_args) self._last_result = result end = datetime.datetime.utcnow()", "in the parameters definition for this sensor to be set. Throws exception if", "m = \"No more parameter values left to map\" self.log.debug(m) return m =", "m = m.format(status=status) raise exceptions.ModuleError(m) time.sleep(poll_sleep) status = self.answers_sse_get_status(**sse_args) end = datetime.datetime.utcnow() elapsed", "elapsed = end - start m = \"Finished polling for Server Side Export", "= [ \"Finished polling in: {dt}\", \"clients answered: {info.mr_passed}\", \"estimated clients: {info.estimated_total}\", \"rows", "to: 0. cache_expiration (:obj:`int`, optional): Have the API keep the cache_id that is", "m = \"Parameter {p.key!r} value {p.value!r} is empty, definition: {d}\" m = m.format(p=param,", "m = \", \".join(m) m = m.format(dt=elapsed, info=info, c=poll_count) self.log.info(m) return infos def", "question. Args: value (:obj:`str`): Filter sensor rows returned on this value. operator (:obj:`str`,", "self._result = result self._last_result = result def __repr__(self): \"\"\"Show object info. Returns: (:obj:`str`)", "\"\"\" now_dt = datetime.datetime.utcnow() now_td = datetime.timedelta() ret = { \"expiration\": now_dt, \"expire_in\":", "= data.cache_id cmd_args[\"row_start\"] += page_size m = [ \"Received initial answers: {d.rows}\", \"expected", "self.api_objects.module_dt_format(self.obj.expiration) is_ex = now_dt >= ex_dt ret[\"expiration\"] = ex_dt ret[\"expired\"] = is_ex if", "format and get an export_id. Args: leading (:obj:`str`, optional): Prepend this text to", "break if status[\"status\"] == \"completed\": m = \"Server Side Export completed: {status}\" m", "\"export/{export_id}.gz\".format(export_id=export_id) client_args[\"data\"] = \"\" r = self.adapter.api_client(**client_args) m = [\"Received SSE data response\",", "optional): Have the API include the hashes of rows values. Defaults to: False.", "k in keys] else: vals = [] return vals def set_filter( self, value,", "N percent. Defaults to: 99. poll_secs (:obj:`int`, optional): If not 0, wait until", "kwargs: Passed to :meth:`tantrum.adapter.Adapter.cmd_add_parsed_question`. Returns: :obj:`Question` \"\"\" if index: pq = self.obj[index] m", "def map_group_params(self, pq, group): \"\"\"Map parameters to filters on the right hand side", "= OrderedDict() for k in self.params_defined: ret[k] = \"\" for p in self.params:", "= m.format(c=total_rows) log.info(m) break page_count += 1 row_start += row_count paging_get_args[\"row_start\"] = row_start", ":attr:`Sensor.param_keys`. Defaults to: True. \"\"\" param_def = self.params_defined.get(key, None) if param_def is None:", "from :meth:`Clients.build_last_reg_filter`. Defaults to: None. sort_fields (:obj:`str`, optional): Attribute of a ClientStatus object", "= datetime.datetime.utcnow() poll_count = 0 sse_args = {} sse_args.update(kwargs) sse_args[\"export_id\"] = export_id status", "= self return select class Question(Workflow): def __str__(self): \"\"\"Show object info. Returns: (:obj:`str`)", "\"Operator {o!r} is invalid, must be one of {vo}\" m = m.format(o=operator, vo=list(OPERATOR_MAP.keys()))", "the API keep the cache of clients for this many seconds before expiring", "to: True. delim (:obj:`str`, optional): String to put before and after parameter key" ]
[ "import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset", "heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK ==", "x 1 x H x W x 2 sample_locs = sample_locs[:, 0, :,", "the 3d coord with the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3])", "(w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w =", "= ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 =", "* visibility normed_pred = normed_pred * visibility delta = normed_pred - normed_3d print(delta)", "Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)),", "= inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im =", "= H self.W = W def mouse_down(self, event): if not event.inaxes: return x,", "print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2)", "# other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file =", "= make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import", "ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_3dpoints, visibility,", "aligns the 3d coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0)", "class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax =", "w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) #", "= 20 thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value =", "# 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT'", "= inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path =", "cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\"", "batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W", "# the vert line # text location in axes coords self.txt = sample_ax.text(0,", "corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] =", "draw_auc(predictions, pck, auc_path) total = 0 for inputs, pred in predictions: heatmap =", "image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img')", "ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view # ax3.set_xlim([-3,", "debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0,", "import imresize sample_size, fh, fw = score.shape resized_img2 = imresize(img2, (fh, fw)) max_score", "= Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx,", "select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point", ":, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score)", "inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0]", "/ (w1.max() - w1.min()) # w2 = corr_pos[:, :, 1] # w2 =", "sim = pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT,", "ax1_2.imshow(img2) w = corr_pos[:, :, 0] w = (w - w.min()) / (w.max()", "i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot)", "plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos')", "coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the", "select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2,", "= p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max() - depth.min()) + 1", "depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx =", "= fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w - w.min()) /", "0] # batchdata['img']: 1 x 4 x 3 x 256 x 256 input_img", "import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax =", "dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred in predictions: while True:", "ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0))", "= heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b,", "in range(fh): for j in range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1", ": RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred:", "inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m',", "import torch # from .ipv_vis import * from vision.triangulation import triangulate from vision.multiview", "# update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw()", "print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections, start, vec =", "= (w - w.min()) / (w.max() - w.min()) # ax2_1 = fig.add_subplot(326) #", "'', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H self.W = W self.axs", "plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos:", "if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img", "\"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt +=", "vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix from core import cfg from", "axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred", "the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns", "'h36m', 'images.zip@', 'images', image_path) # from utils import zipreader # data_numpy = zipreader.imread(", "0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return", "circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ)", "(x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap", "img[..., 1, :, :] * 0.224 + 0.456 img[..., 2, :, :] =", "circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax,", "::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0,", "pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2,", "# for inputs, pred in predictions: while True: inputs, pred = predictions[cnt] heatmap", "-1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2,", "int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d,", "'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred':", "KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img", "H self.W = W def mouse_down(self, event): if not event.inaxes: return x, y", "MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0]", "sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt", "img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output = {", "inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path", "= pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT,", "= plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(),", "location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth =", "class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx", "\"\"\" KRT: corr_pos: feat_h x feat_w x 2 score: sample_size x feat_h x", "# the horiz line self.ly = sample_ax.axvline(color='k') # the vert line # text", "# aligns the 3d coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred,", "circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax,", "predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img')", "0 # for inputs, pred in predictions: while True: inputs, pred = predictions[cnt]", "RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred: sample_locs", "# aligns the 3d coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred,", "w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w)", "3d coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0,", "= np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point =", "feat_w x 2 score: sample_size x feat_h x feat_w \"\"\" y = np.arange(0,", "# W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0))", "print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty,", "isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel =", "# batchdata['img']: 1 x 4 x 3 x 256 x 256 input_img =", "heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints =", "from utils import zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)", "assert img.shape == (1000, 1000, 3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0]", "positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax:", "= inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred =", "'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT, # 'other_RT':", "if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline", "event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:,", "sys, re, cv2, glob, numpy as np import os.path as osp from tqdm", "img[..., 2, :, :] = img[..., 2, :, :] * 0.225 + 0.406", "score.shape resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1", "elev=-90.0) # aligns the 3d coord with the camera view # ax3.set_xlim([-3, 3])", "= fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility,", "np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2", "= sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H self.W", "= inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred =", "p_homo[2] cnt += 1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth = (depth", "# import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1],", "other_image_file, # 'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d':", "...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out,", "grid_corr, grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh,", "imresize sample_size, fh, fw = score.shape resized_img2 = imresize(img2, (fh, fw)) max_score =", "plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar()", "1 depth = np.log(depth) depth = (depth - depth.min()) / (depth.max() - depth.min())", "\"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs, pred in predictions: while", "y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i", "intersections, mask, valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty,", "else: print(sample_locs.shape) # 64 x 1 x H x W x 2 sample_locs", "normed_pred - normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err = ',", "0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not", "= visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred = can_pred * visibility", "other_RT, corr_pos_pred, sim) output = { # 'p3D': p3D, # 'img_pt': img_pt, 'img1':", "def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y)", "plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "= heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2,", "w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth)", "print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved!", "camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "% (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b,", "mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty,", "self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img)", "W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0])", "= self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear()", "fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img)", "= plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:,", "# text location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\")", "image_path = inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT", "'images.zip@', 'images', image_path) # from utils import zipreader # data_numpy = zipreader.imread( #", "visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax):", "can_3dpoints * visibility can_pred = can_pred * visibility normed_3d = normed_3d * visibility", "= inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints =", "sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader", "depth.min()) + 1 depth = np.log(depth) depth = (depth - depth.min()) / (depth.max()", "H x W x 2 sample_locs = sample_locs[:, 0, :, :, :] #", "plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "pred in predictions: while True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred", "cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader =", "grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x =", "H, W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None,", "np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x,", "= outs def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata,", "0.224 + 0.456 img[..., 2, :, :] = img[..., 2, :, :] *", "pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC: ', auc_value)", "\"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR,", "= (depth - depth.min()) / (depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1", "fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->',", "= get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output = { #", "elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2)", "from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True)", "\"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1 # depth = output['depth']", "draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx", "w1 = (w1 - w1.min()) / (w1.max() - w1.min()) # w2 = corr_pos[:,", "pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim)", "from matplotlib.patches import Circle import torch # from .ipv_vis import * from vision.triangulation", "* np.max((KRT1@p3D)[2, :]) cnt = 0 for i in range(fh): for j in", "64 x 1 x H x W x 2 sample_locs = sample_locs[:, 0,", "other_camera, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else:", "self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H = H self.W", "i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty,", "mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from matplotlib.patches import Circle import torch", "- w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 =", "plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max())", "RT, other_RT, corr_pos_pred, sim) output = { # 'p3D': p3D, # 'img_pt': img_pt,", "outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs =", "visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "= 0 for inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d')", "scipy import matplotlib.pyplot as plt from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D", "sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT,", "KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output = { # 'p3D': p3D, #", ":, :] * 0.224 + 0.456 img[..., 2, :, :] = img[..., 2,", "= fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 =", "IPython import embed import scipy import matplotlib.pyplot as plt from skimage.transform import resize", "from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class", "pck, auc_path) total = 0 for inputs, pred in predictions: heatmap = inputs.get('heatmap')", "pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT,", "with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) #", "and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x", "= imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score", "20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos,", "(128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim", "'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, }", "# img = data_numpy[:1000] # assert img.shape == (1000, 1000, 3), img.shape img", "= normed_3d * visibility normed_pred = normed_pred * visibility delta = normed_pred -", "* 0.224 + 0.456 img[..., 2, :, :] = img[..., 2, :, :]", "elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3)", "np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 =", "/ (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w", "# show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0,", "64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx])", ":, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3", "# ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not", "visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5),", "line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in", "and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\"", "inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64,", "self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 ,", "= inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:',", "3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0", "cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import", "KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img", "valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections',", "Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r')", "# w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337)", "#ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 =", "= np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for i in range(fh):", "= 0 for i in range(fh): for j in range(fw): if not select_pos[i*fw+j]:", "::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233)", "event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs =", "not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:,", "np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck,", "= np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2))", "event.inaxes: return x, y = event.xdata, event.ydata # update the line positions self.lx.set_ydata(y)", "vert line # text location in axes coords self.txt = sample_ax.text(0, 0, '',", "= grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh,", "(x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1,", "event): if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) #", "* np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0", "= sample_locs self.H = H self.W = W def mouse_down(self, event): if not", "img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path =", "delta = normed_pred - normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err", "w2 = (w2 - w2.min()) / (w2.max() - w2.min()) # W = np.stack([w1,", "in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event):", "the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d,", "y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a,", "cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE #", "from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax,", "depth.min()) / (depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1)", "np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) >", "with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0,", "/ max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path)", "pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img,", "img[..., 1, :, :] = img[..., 1, :, :] * 0.224 + 0.456", "axs self.img2 = img2 self.outs = outs def mouse_down(self, event): if not event.inaxes:", "((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333)", "fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d')", "'', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H", "axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos =", "cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose()", "dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 =", "axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if", "= fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 =", "pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1,", "= inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\",", "baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\"))", "= resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos],", "import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i)", "0, :, :] = img[..., 0, :, :] * 0.229 + 0.485 img[...,", "self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred", "p3D /= p3D[3] p3D = p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max()", "print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1", "can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global", "= plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1)", "w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] # w1", ", color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show()", "fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235)", "fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w =", "self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw()", "os.path, sys, re, cv2, glob, numpy as np import os.path as osp from", "def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20) pck", "self.ly = sample_ax.axvline(color='k') # the vert line # text location in axes coords", "= grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x", "b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b))", "2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0,", "intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections, mask,", "fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w - w.min()) / (w.max()", "image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 =", ":]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for i", "inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path)", "= cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else", "from sklearn.metrics import auc from matplotlib.patches import Circle import torch # from .ipv_vis", "\"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs,", "imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0,", "fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334,", "pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig", "other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera", "inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth')", "unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred", "= fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2", "cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x,", "import os.path as osp from tqdm import tqdm from IPython import embed import", "import Circle import torch # from .ipv_vis import * from vision.triangulation import triangulate", "W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k')", "inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path),", "pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT,", "0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] =", "for i in range(fh): for j in range(fw): if not select_pos[i*fw+j]: continue p_homo", "1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth = (depth - depth.min()) /", "in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME", "= torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 #", "self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i", "# p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output", "(w2 - w2.min()) / (w2.max() - w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)],", "256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :,", "__init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax", "= select_pos2.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1", "not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from", "sim) output = { # 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2'", "= sample_locs[:, 0, :, :, :] # import pdb; pdb.set_trace() fig, axs =", "pck, auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck,", "= np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y))", "image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, }", "grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE)", "= event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs", "- w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w = select_img_point[:,", "dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs, pred", "= fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img", "...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:,", "self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1,", "/ (depth.max() - depth.min()) + 1 depth = np.log(depth) depth = (depth -", "= corr_pos[:, :, 1] # w2 = (w2 - w2.min()) / (w2.max() -", "self.sample_locs = sample_locs self.H = H self.W = W self.axs = axs self.img2", "cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3", "2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64,", "de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self,", "= Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1,", "sample_locs self.H = H self.W = W self.axs = axs self.img2 = img2", "glob, numpy as np import os.path as osp from tqdm import tqdm from", "self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy =", "= Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs,", "= p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1", "heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a,", "(w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w =", "cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr =", "yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear()", "= select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w - w.min()) / (w.max()", "= sample_ax.axvline(color='k') # the vert line # text location in axes coords self.txt", ":] = img[..., 2, :, :] * 0.225 + 0.406 return img def", "\"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck,", "- normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean())", "if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel", "cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from", "coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred =", "= predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT =", "pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]],", "W def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata", "get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x", "im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ =", "= pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 *", "image_path) # from utils import zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR", "# w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338)", "84 grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y", "64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx])", "3d coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns", "x 3 x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4]", "not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor)", "'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1,", "grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh, fw = score.shape resized_img2 =", "print(sample_locs.shape) # 64 x 1 x H x W x 2 sample_locs =", "if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume", "= Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[...,", "baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\" predictions", "xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume),", "data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader))", "= np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE *", "print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1)", "cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation',", "KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,", "pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0)", "\"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1)", "sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the", "name = \"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\"))", "= inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global =", "colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir", "sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to", "pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for", "w1.min()) / (w1.max() - w1.min()) # w2 = corr_pos[:, :, 1] # w2", "RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w x 2 score:", "imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score >", "# circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax,", "0.225 + 0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds", "ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and", "the 3d coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) #", "heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[..., None]", "# select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :]", "= ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3", "fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def", "print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0,", "w2 = corr_pos[:, :, 1] # w2 = (w2 - w2.min()) / (w2.max()", "ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w - w.min())", ":] = img[..., 1, :, :] * 0.224 + 0.456 img[..., 2, :,", "select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20", ": other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred,", "def de_transform(img): img[..., 0, :, :] = img[..., 0, :, :] * 0.229", "p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid)", "= event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' %", "other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\",", "grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid =", "- w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw)", "# data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000]", "KRT: corr_pos: feat_h x feat_w x 2 score: sample_size x feat_h x feat_w", "* from vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix from core import", "if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x,", "plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :,", "p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir =", "* visibility normed_3d = normed_3d * visibility normed_pred = normed_pred * visibility delta", "(fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02", "text location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs", "matplotlib.pyplot as plt from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics", "numpy as np import os.path as osp from tqdm import tqdm from IPython", "_, _, debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs',", "20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1)", "corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt =", "force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M:", "= sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f:", "= img[..., 2, :, :] * 0.225 + 0.406 return img def draw_auc(predictions,", "resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0]", "+= 1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth = (depth - depth.min())", "'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT'", "i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx])", "plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W =", "inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path)", "zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img =", "de_transform(img): img[..., 0, :, :] = img[..., 0, :, :] * 0.229 +", "batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x:", "3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path',", "break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if", "a, b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a,", "x feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128 x =", "= fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1", "0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W):", "not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt]) p = p_homo /", "sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax =", "inty, intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs", "0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2,", "sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in", "(w1.max() - w1.min()) # w2 = corr_pos[:, :, 1] # w2 = (w2", "(depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 =", "corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w x 2 score: sample_size x", "draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax", "self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for", "elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets',", "pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im,", "# ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns", "= (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w", "sample_locs, H, W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx", "scipy.misc import imresize sample_size, fh, fw = score.shape resized_img2 = imresize(img2, (fh, fw))", "fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) #", "# from .ipv_vis import * from vision.triangulation import triangulate from vision.multiview import pix2coord,", "(w - w.min()) / (w.max() - w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w)", "= pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image =", "2, :, :] * 0.225 + 0.406 return img def draw_auc(predictions, pck, auc_path):", "self.axs = axs self.img2 = img2 self.outs = outs def mouse_down(self, event): if", "sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k') # the vert line #", "pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ', 'baseline_'", "the 3d coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3)", "x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0,", "w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis #", "cnt = 0 for i in range(fh): for j in range(fw): if not", "(w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0]", "= de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2", "camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plt.show() print(\"show\")", "elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3)", "= np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :])", "cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[1]) im2=", "if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset", "normed_pred = normed_pred * visibility delta = normed_pred - normed_3d print(delta) print('L1 err", "return img def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold,", ":] * 0.229 + 0.485 img[..., 1, :, :] = img[..., 1, :,", "img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w", "def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names", "'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if", "score): \"\"\" KRT: corr_pos: feat_h x feat_w x 2 score: sample_size x feat_h", "ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints,", "/ (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :,", "image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils import zipreader #", "mask, valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx])", "return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y),", "w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w)", "if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!')", "plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax", "normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig", "sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f:", "= zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert", "show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231)", "ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape)", "img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y", "grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh, fw))", "os.path as osp from tqdm import tqdm from IPython import embed import scipy", "0.485 img[..., 1, :, :] = img[..., 1, :, :] * 0.224 +", "projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0,", "self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw()", "= np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y", "sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR", "cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\",", "torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path", "make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M", "return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)]", "y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1])", "- depth.min()) + 1 depth = np.log(depth) depth = (depth - depth.min()) /", "import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax", "0].clear() axs[1, 0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos,", "- depth.min()) / (depth.max() - depth.min()) + 1 depth = np.log(depth) depth =", "y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap =", "= fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d')", "'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera':", "print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!')", "pred in predictions: while True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d", "corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR:", ":, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img,", ":] # import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0],", "0 for i in range(fh): for j in range(fw): if not select_pos[i*fw+j]: continue", "in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5)", "np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1,", "print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv)", "cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\"))", "depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2,", "grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh, fw = score.shape", "axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) #", "points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d", "corr_pos[:, :, 0] # w1 = (w1 - w1.min()) / (w1.max() - w1.min())", "make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and", "ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(),", "range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b',", "intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0,", "# assert img.shape == (1000, 1000, 3), img.shape img = inputs.get('img') other_KRT =", "def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] = img[..., 0,", "from vision.multiview import pix2coord, coord2pix from core import cfg from vision.multiview import de_normalize", "core import cfg from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand", "= de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1 x H", ":] * 0.224 + 0.456 img[..., 2, :, :] = img[..., 2, :,", "with the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3])", "inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera')", "grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid =", "coord2pix from core import cfg from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose", "score: sample_size x feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128", "np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3", "= 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils import", "batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs", "image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@',", "corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k')", "normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int)", "projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image)", "self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4,", "event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0,", "sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ)", "- w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w", "= imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:,", "hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global", "np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y =", "intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ", "normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale", "select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape)", "Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax", "inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale')", "print('L1 err = ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1)", "cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d'", "= (KRT1 @ p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0],", "p_homo = (KRT1 @ p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)),", "1, :, :] * 0.224 + 0.456 img[..., 2, :, :] = img[...,", "x 2 score: sample_size x feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0])", "score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') #", "pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H,", "de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx,", "fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w =", "32))] = p_homo[2] cnt += 1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth", "view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[2])", "modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0]", "pickle.dump(output,f) print('saved!') cnt += 1 # depth = output['depth'] # corr_pos_pred = output['corr_pos_pred']", "self.H = H self.W = W self.axs = axs self.img2 = img2 self.outs", "grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh, fw", "import cfg from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import", "/ (depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2", "(depth - depth.min()) / (depth.max() - depth.min()) + 1 depth = np.log(depth) depth", "if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST", "0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b',", "W x 2 sample_locs = sample_locs[:, 0, :, :, :] # import pdb;", "draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz", "err = ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1", "/ (w.max() - w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D,", "import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt +=", "KRT1, grid_corr, grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth =", "(a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show()", "= select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total", "3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) #", "grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1)", "= fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w - w.min()) /", "predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap')", "= sample_locs self.H = H self.W = W self.axs = axs self.img2 =", "* visibility can_pred = can_pred * visibility normed_3d = normed_3d * visibility normed_pred", "'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in", "y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap =", "cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth", "np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336)", "elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2)", "resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos])", "if not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt]) p = p_homo", "coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not", "other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera,", "= (depth - depth.min()) / (depth.max() - depth.min()) + 1 depth = np.log(depth)", "other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth':", "inputs, pred in predictions: while True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap')", "y = np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) # 84 grid_x,", "# 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file,", "= batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x", "= self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W)", "'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred: sample_locs =", "axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos))", "= imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img,", "fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1)", "self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap,", "cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:,", "+ \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt", "w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w -", "vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object):", "b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b))", "inty, intx]) for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i,", "axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r')", "os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for inputs, pred", "grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE", "fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 =", "w = corr_pos[:, :, 0] w = (w - w.min()) / (w.max() -", ": other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT, # 'other_RT': other_RT,", "0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H self.W = W", ":, :] = img[..., 2, :, :] * 0.225 + 0.406 return img", "20 thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds,", "x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] = img[..., 0, :, :] *", "= pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred,", "= fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w = (w - w.min())", "image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred", "_, _, _, debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs print(intx, inty)", "feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) #", "ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0)))", "::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1", "i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True,", "# corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in", "in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs", "x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img =", "x feat_w x 2 score: sample_size x feat_h x feat_w \"\"\" y =", "ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1", "max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3", "pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK", "import pix2coord, coord2pix from core import cfg from vision.multiview import de_normalize from vision.visualizer_human", "plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "Axes3D from sklearn.metrics import auc from matplotlib.patches import Circle import torch # from", "pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img,", "fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w =", "= heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b,", "self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H", "ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] # w1 = (w1 - w1.min())", "self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap,", "print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos))", "cnt += 1 # depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs", "axs, img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') #", "line # text location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\",", "inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections,", "pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT", "= inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img", "inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side')", "pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y))", "= np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2", "valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty,", "output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as", "# w2 = (w2 - w2.min()) / (w2.max() - w2.min()) # W =", "- w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw)", "x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs", "64, 64, 2)[0, inty, intx]) for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)]", "import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for", "class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax", "event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y))", "de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0])", "fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR,", "fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338,", "\"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred in", "= output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from", "the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plt.show()", "\"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total", "== 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 =", "de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1])", "sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line self.ly =", "W self.axs = axs self.img2 = img2 self.outs = outs def mouse_down(self, event):", "# for inputs, pred in predictions: while True: inputs, pred = predictions[cnt] print('input", "', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331)", "np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE", "return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] = img[..., 0, :, :]", "= select_pos1.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1", "grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x *", "w = (w - w.min()) / (w.max() - w.min()) # ax2_1 = fig.add_subplot(326)", ":, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir", ":, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig =", "> 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3,", "idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda", "event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x,", "# ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64", ":10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w - w.min()) / (w.max() - w.min())", "= (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w", "cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x", "cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth", "= inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path)", "\"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred in predictions: while", "output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck", "2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE *", "alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ", "self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _,", "event): if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume", "in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64): pos", "= corr_pos_pred self.sample_locs = sample_locs self.H = H self.W = W def mouse_down(self,", "RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth':", "ha=\"left\") self.sample_locs = sample_locs self.H = H self.W = W self.axs = axs", "> -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos", "0] # w1 = (w1 - w1.min()) / (w1.max() - w1.min()) # w2", "Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] #", "# depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) *", "outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down)", "in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True)", "if not event.inaxes: return x, y = event.xdata, event.ydata # update the line", "= grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2,", "import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0],", "= normed_pred * visibility delta = normed_pred - normed_3d print(delta) print('L1 err =", "84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image", "= plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 =", "img.shape == (1000, 1000, 3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] #", "- depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332)", "* 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE", ":, 1] # w2 = (w2 - w2.min()) / (w2.max() - w2.min()) #", "other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred", "heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path", "'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs'", "= plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 =", "= grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos,", "self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[1])", "dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline", "batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x 3 x 256 x 256", "\"\"\" y = np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) # 84", "ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) #", "+= 1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred =", "with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ', 'baseline_' +", "cnt += 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) #", "matplotlib.patches import Circle import torch # from .ipv_vis import * from vision.triangulation import", "= img[..., 1, :, :] * 0.224 + 0.456 img[..., 2, :, :]", "range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos =", "pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5)", "np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE)", "- w2.min()) / (w2.max() - w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0)", "ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w - w.min()) / (w.max() -", "= batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4]", "pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1", "# for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu", "'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred')", "coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the", "w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w)", "plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "= (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) #######", "as plt from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import", "(depth.max() - depth.min()) + 1 depth = np.log(depth) depth = (depth - depth.min())", "corr_pos[:, :, 1] w = (w - w.min()) / (w.max() - w.min()) ax1_1", "osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils import zipreader # data_numpy =", "yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :,", "path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT =", "projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d')", "+= 1 # depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs =", "can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image", "inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@',", "depth = (depth - depth.min()) / (depth.max() - depth.min()) #######vis fig = plt.figure(1)", "MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader", "is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader", "auc_value = auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0,", "data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m", "w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w - w.min()) /", "from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax", "show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :,", ":, :] = img[..., 1, :, :] * 0.224 + 0.456 img[..., 2,", "self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap,", "other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output = { # 'p3D': p3D,", "= fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max())", "heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs", "self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line", "image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im", "i in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ =", "for inputs, pred in predictions: while True: inputs, pred = predictions[cnt] heatmap =", "toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] = img[..., 0, :,", "= resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred =", "fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns", "get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output = { # 'p3D':", "mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x)", "inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img =", "print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred')", "text location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def", "ha=\"left\") def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata", "ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w - w.min())", "alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return", "\"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred in predictions: while True: inputs,", "np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos", "w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w -", "batchdata['img']: 1 x 4 x 3 x 256 x 256 input_img = batchdata['img'].squeeze()[None,", "max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC:", "print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0]", "ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w -", "points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image", "= plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs,", "# w = (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339)", "0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def", "from tqdm import tqdm from IPython import embed import scipy import matplotlib.pyplot as", "import matplotlib.pyplot as plt from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from", "__init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') #", "* cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE", "import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ',", "orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0],", "cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR,", "import zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img", "continue p_homo = (KRT1 @ p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1],", "the 3d coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3)", "vec.view(-1, 64, 64, 2)[0, inty, intx]) for i in range(64): # pos =", "view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "= batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H,", "inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path')", "sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') #", "w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) #", "inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d')", "% (a, b)) a, b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot)", "int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f,", "view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1)", "print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0,", "keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred", "batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT,", "im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y,", "ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self,", "event): if not event.inaxes: return x, y = event.xdata, event.ydata # update the", "dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for inputs, pred in predictions:", "in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos", "int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f'", "inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0]", "p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file,", ":, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1,", "\"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\",", "axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0,", ":, :] # import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus =", "64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec',", "if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total =", "np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import", "inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap')", "circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ =", "b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class", "output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR,", "pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ", "import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def", "print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT", "b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b))", "inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64,", "thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck)", "= (w1 - w1.min()) / (w1.max() - w1.min()) # w2 = corr_pos[:, :,", "(w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w", "inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred')", "= \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\" predictions =", "visibility can_pred = can_pred * visibility normed_3d = normed_3d * visibility normed_pred =", "1, :, :] = img[..., 1, :, :] * 0.224 + 0.456 img[...,", "import * from vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix from core", "= fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w", "x 4 x 3 x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :,", "= inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path =", "= img2 self.outs = outs def mouse_down(self, event): if not event.inaxes: return x,", "= depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H = H self.W =", "fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt =", "# ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if", "cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r')", "fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for i in range(fh): for j", "print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2,", "self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" %", "- w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis", "target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility", "- w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w", "self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx", "print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs =", "camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility,", "= can_3dpoints * visibility can_pred = can_pred * visibility normed_3d = normed_3d *", "draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k') # the", "normed_3d * visibility normed_pred = normed_pred * visibility delta = normed_pred - normed_3d", "the 3d coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) #", "= fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) #", "cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if", "int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections, start,", "W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0)))", "= pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x,", "intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2,", "= de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0],", "grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x =", "self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f", "imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img,", "self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x,", "visibility normed_3d = normed_3d * visibility normed_pred = normed_pred * visibility delta =", "\"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path =", "print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 =", "/ (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w", "resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos')", "sim, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else:", "True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT =", "as f: pickle.dump(output,f) print('saved!') cnt += 1 # depth = output['depth'] # corr_pos_pred", "from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from matplotlib.patches import Circle import", "RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128,", "other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file =", "i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)]", "* cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr", "= inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera =", "(depth - depth.min()) / (depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1 =", "cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE *", "print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D =", "cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr *", "axs[1, 0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H,", "= pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() # p3D,", "de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1],", "inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0]", "# depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if", "0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _,", "in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0]) im1=", "torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for", "# aligns the 3d coord with the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0,", "plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0)", "tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) #", "'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' :", "fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T)", "int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections, start, vec", "= pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb;", "import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from matplotlib.patches import", "'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred", "torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions,", "ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2", "ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else:", "= sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs", "image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0]", "'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera':", "= \"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR,", "import auc from matplotlib.patches import Circle import torch # from .ipv_vis import *", "= Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0]", "(w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w =", "with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1 #", "import os.path, sys, re, cv2, glob, numpy as np import os.path as osp", "= pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img,", "= W self.axs = axs self.img2 = img2 self.outs = outs def mouse_down(self,", "print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs, pred in predictions:", "sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax", "_, debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:,", "debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']:", "image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape == (1000,", "circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img):", "= pred.get('normed_pred') heatmap_pred = pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int) if", "print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def", "= W def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata,", "ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] # w1 =", "np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt", "horiz line self.ly = sample_ax.axvline(color='k') # the vert line # text location in", "yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx,", "64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for", "= inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other", "w = select_pos1.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min())", "# 128 x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y)", "ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w = (w -", "p3D = p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max() - depth.min()) +", "KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path)", "fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w = (w - w.min()) /", "H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :,", "inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit')", "= fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 =", "resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 =", "img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0]", "depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2)", "+ 0.456 img[..., 2, :, :] = img[..., 2, :, :] * 0.225", "> 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 =", "update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for", "resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from matplotlib.patches import Circle", "ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST", "as osp from tqdm import tqdm from IPython import embed import scipy import", "2 sample_locs = sample_locs[:, 0, :, :, :] # import pdb; pdb.set_trace() fig,", "cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape == (1000, 1000, 3), img.shape", "# cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' %", "= (w2 - w2.min()) / (w2.max() - w2.min()) # W = np.stack([w1, w2,", "total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred", "predictions: while True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys())", "#ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "as np import os.path as osp from tqdm import tqdm from IPython import", "self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes:", "np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold", "ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H = H", "= normed_pred - normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err =", "plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\", "H, W, axs, img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx =", "self.outs = outs def mouse_down(self, event): if not event.inaxes: return x, y =", "= event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0,", "fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2", "corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt =", "(a, b)) a, b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\"", "p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2]", "pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y,", "H self.W = W self.axs = axs self.img2 = img2 self.outs = outs", "inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64,", "other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path)", ":, 1] w = (w - w.min()) / (w.max() - w.min()) ax1_1 =", "\\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im", "axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions", "# ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD", "= cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) #", "= self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy))", "= corr_pos[:, :, 0] w = (w - w.min()) / (w.max() - w.min())", "make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False,", "fw = score.shape resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh,", "= fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) #", "= predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap =", "#######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w", "import scipy import matplotlib.pyplot as plt from skimage.transform import resize from mpl_toolkits.mplot3d import", "/ (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1]", "output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build", "1] # w2 = (w2 - w2.min()) / (w2.max() - w2.min()) # W", "cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr", "plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2,", "print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT", "for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ", "Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax =", "from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M:", "2).transpose() from scipy.misc import imresize sample_size, fh, fw = score.shape resized_img2 = imresize(img2,", "self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)]", "+ 0.485 img[..., 1, :, :] = img[..., 1, :, :] * 0.224", "plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs):", "va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata,", "other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images',", "start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx])", "dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR,", "pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt", "other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred,", "= Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show()", "start, vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1,", "other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs'", "event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y),", "vision.multiview import pix2coord, coord2pix from core import cfg from vision.multiview import de_normalize from", "range(fh): for j in range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1 @", "force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader =", "ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d')", "orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0],", "# prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names", "image_file, 'img2_path': other_image_file, # 'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap':", "- w1.min()) / (w1.max() - w1.min()) # w2 = corr_pos[:, :, 1] #", "- w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336)", "2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for i in", "np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2", "inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera')", "sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img =", "= fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 =", "grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size,", "sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr,", "visibility normed_pred = normed_pred * visibility delta = normed_pred - normed_3d print(delta) print('L1", "in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True)", "in predictions: while True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d =", "depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D /= p3D[3] p3D", "ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0)", "'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred':", "= fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w", "print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d')", ":, 0] w = (w - w.min()) / (w.max() - w.min()) ax1_1 =", "axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs,", "axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0])", "= inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred", "open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt))", "x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel =", "j in range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt])", "inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty,", "camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the", "'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT,", "img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat", "inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5)", "ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel", "= torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 #", "sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H self.W =", "ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show()", "0 for inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side", "pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)]", "output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\")", "\"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for inputs, pred in predictions: heatmap", "data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if not", "# 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path,", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1)", "ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0,", "= fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0)", "# ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw)", "w = (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w)", "vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w -", "num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC: ',", "fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H,", "cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt =", "# break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show()", "# image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape ==", "self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H,", "self.sample_locs = sample_locs self.H = H self.W = W def mouse_down(self, event): if", "# circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b',", "'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in", "= cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2,", "np.max((KRT1@p3D)[2, :]) cnt = 0 for i in range(fh): for j in range(fw):", "'images', image_path) # from utils import zipreader # data_numpy = zipreader.imread( # image_file,", "input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,", "import embed import scipy import matplotlib.pyplot as plt from skimage.transform import resize from", "(w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end", "= np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc", "fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0))", "def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h", "'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import", "and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions =", ":, :] * 0.225 + 0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold", "data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from", "print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0,", "event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx,", "w = corr_pos[:, :, 1] w = (w - w.min()) / (w.max() -", "# data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if", "axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2)", "va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H = H self.W = W self.axs =", "cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif", "pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076", "= np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 =", "normed_3d = normed_3d * visibility normed_pred = normed_pred * visibility delta = normed_pred", "'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT':", "def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k')", "fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img =", "ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_3dpoints,", "# w2 = corr_pos[:, :, 1] # w2 = (w2 - w2.min()) /", "img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT,", "% (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ)", "pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs')", "= de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:,", "(w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1", "sample_locs self.H = H self.W = W def mouse_down(self, event): if not event.inaxes:", "= make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M", "im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y,", "0] w = (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334)", "} if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No", "0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs =", "not event.inaxes: return x, y = event.xdata, event.ydata # update the line positions", "sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs =", "cnt = 0 # for inputs, pred in predictions: while True: inputs, pred", "torch.Tensor) else x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True)", "location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs =", "+ \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1 # depth =", "{ # 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path':", "f: pickle.dump(output,f) print('saved!') cnt += 1 # depth = output['depth'] # corr_pos_pred =", "can_3dpoints = can_3dpoints * visibility can_pred = can_pred * visibility normed_3d = normed_3d", "* 0.225 + 0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold = 20", "fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m'", "* cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr", "= Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1", "= corr_pos[:, :, 0] # w1 = (w1 - w1.min()) / (w1.max() -", "pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1])", "(w.max() - w.min()) ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w =", ":] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D", "w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:,", "auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for", "not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume =", "= make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg,", "= np.log(depth) depth = (depth - depth.min()) / (depth.max() - depth.min()) #######vis fig", "self.W = W def mouse_down(self, event): if not event.inaxes: return x, y =", "1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions =", "= pred.get('heatmap_pred') im = plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint':", "can_pred * visibility normed_3d = normed_3d * visibility normed_pred = normed_pred * visibility", "= inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale =", "dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\",", ":, :] * 0.229 + 0.485 img[..., 1, :, :] = img[..., 1,", "% (a, b)) a, b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot)", "auc from matplotlib.patches import Circle import torch # from .ipv_vis import * from", "inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84,", "cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\"", "print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx])", "def __init__(self, sample_ax, draw_ax, sample_locs, H, W, axs, img2, outs): self.sample_ax = sample_ax", "= { # 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img,", "torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for", "aligns the 3d coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility,", "in range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt]) p", "inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for i in range(64):", "visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "'depth': sim, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs", "0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x 3 x", "points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera,", "- w1.min()) # w2 = corr_pos[:, :, 1] # w2 = (w2 -", "w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :,", "cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1 # depth = output['depth'] #", "= Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :,", "axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w =", "cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid", "# w1 = (w1 - w1.min()) / (w1.max() - w1.min()) # w2 =", "# 64 x 1 x H x W x 2 sample_locs = sample_locs[:,", "select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos',", "select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D", "select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt]) p = p_homo / p_homo[2]", "not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\",", "enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if", "camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "sample_locs[:, 0, :, :, :] # import pdb; pdb.set_trace() fig, axs = plt.subplots(2,", "ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view # ax3.set_xlim([-3,", "i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\"", "0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds = np.linspace(0,", "else x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0", "sklearn.metrics import auc from matplotlib.patches import Circle import torch # from .ipv_vis import", "= axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST", "= np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value = auc(thresholds, pck) /", "3d coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns", "#ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility =", "= inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@'", "while True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT", "make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) elif cfg.VIS.H36M: from data.datasets.joints_dataset import", "RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w x 2 score: sample_size", "plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR:", "np import os.path as osp from tqdm import tqdm from IPython import embed", "% (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw()", "ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_pred, visibility,", "KRT1, grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth =", "to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv) #", "\"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for inputs, pred in", "(w.max() - w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point", "'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR,", "p3D[3] p3D = p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max() - depth.min())", "ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_pred,", "predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0", "ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w = (w", "path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred", "corr_pos[:, :, 0] w = (w - w.min()) / (w.max() - w.min()) ax1_1", "cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt", "pdb.set_trace() fig, axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs,", "i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy()", "img = data_numpy[:1000] # assert img.shape == (1000, 1000, 3), img.shape img =", "p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim) output =", "fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) >", "int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x):", "'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred':", "depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H = H self.W = W", "# ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0,", "ax1_1.imshow(w) w = corr_pos[:, :, 1] w = (w - w.min()) / (w.max()", "\"predictions.pth\")) cnt = 0 # for inputs, pred in predictions: while True: inputs,", "vec = self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64,", "np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for i in range(fh): for", "batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR:", "'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs':", "+ 0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds =", "sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output,", "= inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit =", "for j in range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:,", "0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W)", "= fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else:", "Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0,", "select_pos.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1 =", "= pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_' +", "print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader =", "is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0]", "select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w - w.min()) / (w.max() -", "KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w x", "axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H", "img def draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20)", "cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4", "img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT,", "b)) a, b, heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" %", "for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y,", "max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20) pck = np.sum(pck, axis=0) auc_value", "intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for i in range(64): #", "in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy()", "a, b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a,", "depth=%.5f\\nCorr xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in", "inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path')", "np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw,", "other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT, # 'other_RT': other_RT, 'heatmap':", "draw_auc(predictions, pck, auc_path): max_threshold = 20 thresholds = np.linspace(0, max_threshold, num=20) pck =", "output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M:", "img1.shape[0]) # 128 x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x,", "dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs, pred in predictions: while True:", "data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader", "end vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w", "visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy", "other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path),", "p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D /= p3D[3]", "', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 =", "sample_size x feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128 x", "batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x 3", "x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)]", "projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d')", "img2, outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the", "# sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import", "(KRT1 @ p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))]", "other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3))", "camera, 'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] =", "'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] #", "def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata #", "1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ)", "auc_path) total = 0 for inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d", "ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image)", "visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred = can_pred *", "grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668 * 4076 grid_corr =", "skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from matplotlib.patches", "import tqdm from IPython import embed import scipy import matplotlib.pyplot as plt from", "in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle", "- w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] #", "ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1", "if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "ax2_1 = fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w - w.min())", "', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv,", "inputs, pred in predictions: while True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys())", "+ \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt,", "# ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m'", ":, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir =", "batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs')", "cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else", "in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\",", "ax1_1 = fig.add_subplot(331) ax1_1.imshow(img1) ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0]", "64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections',", "1] w = (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335)", "# ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR", "True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader", "# outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs", "= torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC:", "@ p3D[:, cnt]) p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] =", "inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file", "ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1 x H x W x", "'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs", "= pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs =", "256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None,", ":, 0] # w1 = (w1 - w1.min()) / (w1.max() - w1.min()) #", "= fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336,", "err = ', ((delta**2).sum(-1)**0.5).mean()) fig = plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332)", "- w.min()) / (w.max() - w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show()", "fh, fw = score.shape resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1),", "visibility = inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred", "# p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh, fw)) *", "img[..., 2, :, :] * 0.225 + 0.406 return img def draw_auc(predictions, pck,", "pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\")", "* 0.229 + 0.485 img[..., 1, :, :] = img[..., 1, :, :]", "print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints", "else: print('No sample_locs!!!!!') import pickle with open('baseline_' + \"output_{:d}.pkl\".format(cnt),\"wb\") as f: pickle.dump(output, f)", "debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None,", "self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0])", "= de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ =", "f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break #", "= p_homo[2] cnt += 1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth =", "heatmap = heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) #", "cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name", "= cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name = \"_baseline\"", "= inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path)", "::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1 x H x W", "= 0 # for inputs, pred in predictions: while True: inputs, pred =", "depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS:", "fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333,", "None] can_3dpoints = can_3dpoints * visibility can_pred = can_pred * visibility normed_3d =", "0.229 + 0.485 img[..., 1, :, :] = img[..., 1, :, :] *", "# ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w", "auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0,", "'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs']", "y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear()", "= draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k') #", "in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth = depth", "print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) #", "pix2coord, coord2pix from core import cfg from vision.multiview import de_normalize from vision.visualizer_human import", "Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx =", "y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs =", "i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64): pos = sample_locs[i][int(y)][int(x)] depos", "output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline = \"baseline\" in cfg.VIS.SAVE_PRED_NAME name =", "100).transpose(1,2,0) # w = (w - w.min()) / (w.max() - w.min()) # ax2_1", ":] * 0.225 + 0.406 return img def draw_auc(predictions, pck, auc_path): max_threshold =", "pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy", "in range(64): pos = sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]),", "return x, y = event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x)", "axs[1, 0].add_patch(circ) plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :]", "64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start',", "pred: sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with", "y = event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f'", "depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1,", ":, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:]", "1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: #", "0], batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0,", "ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w - w.min()) / (w.max() -", "y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H, W,", "= inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) #", "= select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D =", "cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im =", "0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes: return x, y", "print('saved!') cnt += 1 # depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] #", "y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty,", ":, :, :] # import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2) cus", "= inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility =", "visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "from IPython import embed import scipy import matplotlib.pyplot as plt from skimage.transform import", "dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path)", "cfg.VIS.H36M: cpu = lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar", "/ (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w", "data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader =", "= inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path =", "make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata", "img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path", "'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs =", "ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs,", "xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2)", "Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x", "cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr =", "'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D,", "x H x W x 2 sample_locs = sample_locs[:, 0, :, :, :]", "data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader =", "plt.show() else: print(sample_locs.shape) # 64 x 1 x H x W x 2", "# aligns the 3d coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0,", "__init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax =", "can_pred = can_pred * visibility normed_3d = normed_3d * visibility normed_pred = normed_pred", "aligns the 3d coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility,", "= inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m',", "pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt", ":][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event',", "other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred')", "fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0))", "data_numpy[:1000] # assert img.shape == (1000, 1000, 3), img.shape img = inputs.get('img') other_KRT", "w1.min()) # w2 = corr_pos[:, :, 1] # w2 = (w2 - w2.min())", ":] = img[..., 0, :, :] * 0.229 + 0.485 img[..., 1, :,", "intx]) for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0,", "# show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 =", "b)) a, b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" %", "H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r')", "select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR", "#ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335,", "if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg,", "fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) # w = (w - w.min()) / (w.max()", "* visibility delta = normed_pred - normed_3d print(delta) print('L1 err = ', np.abs(delta).sum())", "self.lx = sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k') # the vert", "heatmapat(x, y, weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0,", "', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1,", "3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path", "other_KRT, RT, other_RT, corr_pos_pred, sim) output = { # 'p3D': p3D, # 'img_pt':", "= lambda x: x.cpu().numpy() if isinstance(x, torch.Tensor) else x from modeling.layers.epipolar import Epipolar", "weights[2]) im3= self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ", "inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred') normed_pred = pred.get('normed_pred')", "yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax:", "fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4", "draw_2d_pose from vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax =", "w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w = select_pos.reshape(fh,fw) #", "osp from tqdm import tqdm from IPython import embed import scipy import matplotlib.pyplot", "1000, 3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0]", "'', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes: return x, y =", "'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs') output['sample_locs']", "cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x, y, weights[2]) im3=", "= cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\",", "plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax = draw_ax", "depth.min()) / (depth.max() - depth.min()) + 1 depth = np.log(depth) depth = (depth", "'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap,", "inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image", "int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D /= p3D[3] p3D = p3D[:3].squeeze()", "inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred =", "= cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :])", "1 # depth = output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs']", "1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) #", "0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1,", "# 'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d,", "W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1,", "self.img2 = img2 self.outs = outs def mouse_down(self, event): if not event.inaxes: return", "KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT: corr_pos: feat_h x feat_w x 2", "ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in", "points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path", "= inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images',", "100, 100).transpose(1,2,0) # w = (w - w.min()) / (w.max() - w.min()) #", "return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir", "coord with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0)", "x from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 =", "w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg):", "else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt", "camera = inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path =", "# 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim,", "#ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with", "img[..., 0, :, :] * 0.229 + 0.485 img[..., 1, :, :] =", "heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import", "axs[0, 0].imshow(cpu(input_img)[0, :, :, :][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show()", "inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R')", "sample_locs = sample_locs[:, 0, :, :, :] # import pdb; pdb.set_trace() fig, axs", "cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST baseline =", "visualization(cfg): if cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names =", "0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score):", "intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty,", "R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path", "x W x 2 sample_locs = sample_locs[:, 0, :, :, :] # import", "= sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k') # the vert line", "plt.show() def toimg(x): return x.squeeze().numpy().transpose([1,2,0]) def de_transform(img): img[..., 0, :, :] = img[...,", "axs = plt.subplots(2, 2) cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W,", "aligns the 3d coord with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0)", "ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view #", "cnt += 1 p3D /= p3D[3] p3D = p3D[:3].squeeze() depth = (depth -", "= fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0)))", "in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img =", "+ 1 depth = np.log(depth) depth = (depth - depth.min()) / (depth.max() -", "grid_corr[:,select_pos], grid[:,select_pos]) # p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh,", "1 x H x W x 2 sample_locs = sample_locs[:, 0, :, :,", "= inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera = inputs.get('camera') other_camera =", "np.log(depth) depth = (depth - depth.min()) / (depth.max() - depth.min()) #######vis fig =", "ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w = select_img_point[:, :10000].reshape(-1, 100,", "f: pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 #", "in predictions: while True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:')", "if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader", "select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50", "= np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos =", "(128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other", "# fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object):", "1 x 4 x 3 x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0,", "= img[..., 0, :, :] * 0.229 + 0.485 img[..., 1, :, :]", "= H self.W = W self.axs = axs self.img2 = img2 self.outs =", "alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object):", "ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3", "int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr", "print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[...,", "= np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y,", "ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w - w.min()) / (w.max() -", "dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred", "\"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs,", "fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w = (w - w.min()) /", "pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1 # break", "from vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix from core import cfg", "plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1,", "location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self,", "# w = (w - w.min()) / (w.max() - w.min()) # ax2_1 =", "ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc from", "KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img =", "p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr, grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2,", "= corr_pos[:, :, 1] w = (w - w.min()) / (w.max() - w.min())", "coord with the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3,", "0, :, :, :] # import pdb; pdb.set_trace() fig, axs = plt.subplots(2, 2)", "% (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1,", "the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "= input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) #", "corr_pos[:, :, 1] # w2 = (w2 - w2.min()) / (w2.max() - w2.min())", "p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D", "x 2 sample_locs = sample_locs[:, 0, :, :, :] # import pdb; pdb.set_trace()", "# image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from", "data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] #", "fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image)", "img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' :", "= pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR +", "= max_score > 0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2))", "heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] camera", "projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the", "ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_3d, visibility,", "import Axes3D from sklearn.metrics import auc from matplotlib.patches import Circle import torch #", "128 x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y) grid_y", "ax1_2 = fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w = (w -", "img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, # 'RT' : RT, #", "import triangulate from vision.multiview import pix2coord, coord2pix from core import cfg from vision.multiview", "imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 = batchdata['other_KRT'].squeeze()[None,", "ax2_1.imshow(w) ####### end vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w", "W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:,", "= fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image)", "x, y = event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f,", "de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 =", "grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from", "intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64,", "keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d = inputs.get('points-2d') KRT =", "w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w = (w", "self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) #", "range(fw): if not select_pos[i*fw+j]: continue p_homo = (KRT1 @ p3D[:, cnt]) p =", "grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE # 2668", ":][::-1].transpose((1,2,0))) # prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR", "KRT1 = batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x 3 x 256", ": RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred,", "w1 = corr_pos[:, :, 0] # w1 = (w1 - w1.min()) / (w1.max()", "= np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331)", "w2.min()) / (w2.max() - w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) #", "fig.add_subplot(337, projection='3d') ax3_2 = fig.add_subplot(338, projection='3d') ax3_3 = fig.add_subplot(333, projection='3d') ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image)", "data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for", "import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT,", "out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img", "self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1", "xx=%d, yy=%d' % (x, y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax:", "= grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh, fw = score.shape resized_img2", "self.H = H self.W = W def mouse_down(self, event): if not event.inaxes: return", "= de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,", "vision.visualizer_hand import plot_hand_3d class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax = sample_ax self.draw_ax", "# w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w = (w - w.min())", "color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class", "1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0])", "for inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side =", "Circle import torch # from .ipv_vis import * from vision.triangulation import triangulate from", "print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img =", "(a, b)) a, b, heatmap = heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\"", "open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f) print('saved!') cnt += 1 # depth", "ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the", "2 score: sample_size x feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0]) #", "'img2_path': other_image_file, # 'RT' : RT, # 'other_RT': other_RT, 'heatmap': heatmap, 'other_heatmap': other_heatmap,", "= sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes: return", "batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1, outs[2][0]) if", "inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3))", "(w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w =", "64, 2)[0, inty, intx]) for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos", "img2 self.outs = outs def mouse_down(self, event): if not event.inaxes: return x, y", "Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax, draw_ax, sample_locs, H,", "w = (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w)", "= output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if", "rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility') unit", "other_KRT = inputs.get('other_KRT')[0] # other_RT = inputs.get('other_RT')[0] other_image_path = inputs.get('other_img-path')[0] print('other image path',", "= self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx, yy =", "# ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') KRT = inputs.get('KRT')[0] RT = inputs.get('RT')[0]", "outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img", "ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints", "heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints", "the camera view plot_hand_3d(normed_pred, visibility, ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "depos = de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ =", "prob_im = axs[1, 1].imshow(max_score) fig.canvas.mpl_connect('button_press_event', cus.mouse_down) plt.show() return output_dir = cfg.OUTPUT_DIR dataset_names =", "visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view", "yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for", "= output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if", "input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0])", "coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.sample_locs = sample_locs self.H =", "3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1, grid_corr[:,select_pos], grid[:,select_pos]) #", "mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata # update", "np.arange(0, pr_cost_volume.shape[0]) # xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw()", "= fig.add_subplot(332) ax1_2.imshow(img2) w = corr_pos[:, :, 0] w = (w - w.min())", "= inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat =", "inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d')", "with the camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) #", "as f: pickle.dump(output, f) print('saved! to ', 'baseline_' + \"output_{:d}.pkl\".format(cnt)) cnt += 1", "# data_loader = make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] #", "intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections, start, vec = self.outs print(intx,", "score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace() #", "'img1_path': image_path, 'img2_path': other_image_path, 'RT' : RT, 'other_RT': other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim,", "p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max() - depth.min()) + 1 depth", "i in range(fh): for j in range(fw): if not select_pos[i*fw+j]: continue p_homo =", "inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global = inputs.get('points-3d') rot_mat = inputs.get('rotation')", "ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in", "= pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D,", "view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "-1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize sample_size, fh, fw =", "= fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] # w1 = (w1", "Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ)", "other_RT, 'corr_pos_pred': corr_pos_pred, 'depth': sim, } if 'sample_locs' in pred: sample_locs = pred.get('sample_locs')", "= self.outs print(intx, inty) print('debugsample_locs', debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64,", "'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path':", "# 2668 * 4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE", "in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0],", "heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a,", "i in self.draw_ax: i.clear() i.figure.canvas.draw() self.sample_ax.imshow(ref_img) a, b, heatmap = heatmapat(x, y, weights[0])", "ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T)", "Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ = Circle((xx, yy),2,color='r') axs[1, 0].add_patch(circ) plt.show() def", "= select_pos.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1", "= pred.get('corr_pos') sim = pred.get('depth') batch_locs = pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img,", "= debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ =", "- w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:, :, 1] w =", "torch # from .ipv_vis import * from vision.triangulation import triangulate from vision.multiview import", "inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1, 64,", "yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs,", "== (1000, 1000, 3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT", "intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64,", "# pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos,", "axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos =", "(w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w =", "the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0, elev=-90.0) # aligns", "= inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim =", "cfg from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from vision.visualizer_hand import plot_hand_3d", "a, b, heatmap = heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a,", "if not event.inaxes: return x, y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume =", "select_pos2.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1 =", "predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0", "self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) #", "0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self,", "self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear()", "'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333)", "debugsample_locs[:, 0, inty, intx]) print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask',", "for inputs, pred in predictions: while True: inputs, pred = predictions[cnt] print('input keys:')", "visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred = can_pred * visibility normed_3d", "= debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W) orig_img =", "-50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos =", "camera view plot_hand_3d(normed_3d, visibility, ax3_3) plot_hand_3d(normed_pred, visibility, ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the", "inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path)", "* cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1,", "# w1 = corr_pos[:, :, 0] # w1 = (w1 - w1.min()) /", "data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))):", "ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names", "* cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE) grid_x = grid_x * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE", "2)[0, inty, intx]) for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos =", "print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d", "predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if", "\"_baseline\" if baseline else \"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\",", "= fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 =", "output = { # 'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' :", "- w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(334) ax1_1.imshow(w) w = corr_pos[:,", "outs def mouse_down(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata", "fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) # w = (w - w.min()) / (w.max()", "is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in", "fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337,", "# 84 grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y =", "= sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line self.ly", "2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64,", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 =", "= auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20,", "(w2.max() - w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 =", "xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in", "= inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84, 3)) other_KRT =", "int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5) self.axs[1, 0].add_patch(circ) #", "= sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as", "cv2, glob, numpy as np import os.path as osp from tqdm import tqdm", "tqdm from IPython import embed import scipy import matplotlib.pyplot as plt from skimage.transform", "select_pos1.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min()) ax2_1 =", "tqdm import tqdm from IPython import embed import scipy import matplotlib.pyplot as plt", "max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw) select_pos1 = max_score > 0.02 print('->', np.sum(select_pos1))", "heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in pred: sample_locs", "inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred = pred.get('can_pred')", "= score.shape resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size, -1), axis=0).reshape(fh, fw)", "= resize(plt.imread(image_path), (128, 84, 3)) other_KRT = inputs.get('other_KRT')[0] other_RT = inputs.get('other_RT')[0] other_image_path =", "84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim =", "osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred =", "from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in", "embed import scipy import matplotlib.pyplot as plt from skimage.transform import resize from mpl_toolkits.mplot3d", "fig.add_subplot(335) ax1_1.imshow(w) # w1 = corr_pos[:, :, 0] # w1 = (w1 -", "grid_x, grid_y = np.meshgrid(x, y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y *", "1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility can_pred = can_pred", "zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape", "\"\" predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt =", "text location in axes coords self.txt = sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") self.depth", "= osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils import zipreader # data_numpy", "depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1, 0].add_patch(circ) circ", "- w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def", "inputs.get('other_img-path')[0] print('other image path', other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img", "print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions\"+name+\".pth\")) cnt = 0 # for inputs, pred in predictions:", "outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) #", "::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H, W)", "sample_size, fh, fw = score.shape resized_img2 = imresize(img2, (fh, fw)) max_score = np.max(score.reshape(sample_size,", "ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total +=", "ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord", "select_pos2).reshape(-1) # select_pos = select_pos3 print('-->',np.sum(select_pos)) select_pos = select_pos.reshape(-1) select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos,", "for i in range(64): # pos = self.sample_locs[i][int(y+0.5)][int(x+0.5)] pos = debugsample_locs[i, 0, inty,", "# aligns the 3d coord with the camera view # ax3.set_xlim([-3, 3]) #", "JointsDataset from data.datasets.multiview_h36m import MultiViewH36M data_loader = MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i", "feat_h x feat_w x 2 score: sample_size x feat_h x feat_w \"\"\" y", "H, W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the", "other_image_path) other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred =", "dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\"))", "plt from skimage.transform import resize from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import auc", "3 x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img", "depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for i in", "self.axs[1, 0].add_patch(circ) # circ = Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def", "fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility", "input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1)", "not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img =", "img[..., 0, :, :] = img[..., 0, :, :] * 0.229 + 0.485", "'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred =", "de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1 x H x", "+= 1 # break # ipv_prepare(ipv) # ipv_draw_point_cloud(ipv, p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500)", "p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_path, 'img2_path': other_image_path,", "ax1_1.imshow(image) ax1_2.imshow(image) #ax1_3.imshow(image) #ax2.imshow(image) plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "# from utils import zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR |", "print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for i in range(64): # pos", "inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d')", "utils import zipreader # data_numpy = zipreader.imread( # image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) #", "corr_pos_pred self.sample_locs = sample_locs self.H = H self.W = W def mouse_down(self, event):", "= make_data_loader(cfg, is_train=True, force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx,", "= inputs.get('scale') visibility = inputs.get('visibility') unit = inputs.get('unit') image_path = inputs.get('img-path') can_pred =", "re, cv2, glob, numpy as np import os.path as osp from tqdm import", "p3D, colors=img_pt, pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR:", "1]) circ = Circle((x, y),2,color='r') axs[0, 0].add_patch(circ) plt.show() class Cursor_for_epipolar_line(object): def __init__(self, sample_ax,", "np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw)) * np.max((KRT1@p3D)[2, :]) cnt = 0 for", "= de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs = imgmodel(batchdata['heatmap'][:, 0], batchdata['heatmap'][:,", "32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D /= p3D[3] p3D =", "= osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred", "out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x 1 x", "the horiz line self.ly = sample_ax.axvline(color='k') # the vert line # text location", "predictions: while True: inputs, pred = predictions[cnt] heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d')", "from modeling.layers.epipolar import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None,", "0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) # show_other_img = de_transform(cpu(batchdata['other_img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig", "corr_pos_pred, sim) output = { # 'p3D': p3D, # 'img_pt': img_pt, 'img1': img,", "= MultiViewH36M('datasets', 'validation', True) print(len(data_loader)) for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg,", "64, 2)[0, inty, intx]) print('vec', vec.view(-1, 64, 64, 2)[0, inty, intx]) for i", "w.min()) / (w.max() - w.min()) # ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return", "ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape)", "ax2_1 = fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD", "for i in tqdm(range(len(data_loader))): data_loader.__getitem__(i) data_loader = make_data_loader(cfg, is_train=False)[0] # data_loader = make_data_loader(cfg,", "normed_pred * visibility delta = normed_pred - normed_3d print(delta) print('L1 err = ',", "from core import cfg from vision.multiview import de_normalize from vision.visualizer_human import draw_2d_pose from", "= inputs.get('KRT')[0] RT = inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img =", "line self.ly = sample_ax.axvline(color='k') # the vert line # text location in axes", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] input_other_img = batchdata['other_img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img,", "grid_y)) grid = grid.reshape(2, -1) grid_corr = grid_corr.reshape(-1, 2).transpose() from scipy.misc import imresize", "= np.sum(pck, axis=0) auc_value = auc(thresholds, pck) / max_threshold print('AUC: ', auc_value) plt.plot(thresholds,", "fig.add_subplot(332) ax3 = fig.add_subplot(333) #ax1.imshow(image) print(heatmap.min(), heatmap.max()) print(heatmap_pred.min(), heatmap_pred.max()) ax2.imshow(heatmap.sum(0).T) ax3.imshow(heatmap_pred.sum(0).T) else: total", "ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w = select_pos1.reshape(fh,fw) #", "else: total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints * visibility", "w = select_pos2.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min())", "Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1 =", "= fig.add_subplot(337) ax2_1.imshow(w) w = select_pos2.reshape(fh,fw) # w = (w - w.min()) /", "select_pos3 = np.sum(corr_pos, axis=2) > -50 print('->',np.sum(select_pos2)) select_pos = np.logical_and(select_pos3, select_pos2).reshape(-1) # select_pos", "2, :, :] = img[..., 2, :, :] * 0.225 + 0.406 return", "print(image_path) # image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) #", "other_image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', other_image_path) other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred')", "pred.get('batch_locs') # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred, sim)", "import Epipolar imgmodel = Epipolar() debugmodel = Epipolar(debug=True) KRT0 = batchdata['KRT'].squeeze()[None, 0] KRT1", "= self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f,", "Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred,", "with the camera view plot_hand_3d(can_pred, visibility, ax2_2) ax2_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d", "depth = (depth - depth.min()) / (depth.max() - depth.min()) + 1 depth =", "pt_size=1) # ipv.xyzlim(500) # ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir =", "force_shuffle=True) # data_loader = make_data_loader(cfg, is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)):", "4 x 3 x 256 x 256 input_img = batchdata['img'].squeeze()[None, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,", "for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx =", "plt.savefig(auc_path) plt.show() def get_point_cloud(img1, img2, KRT1, KRT2, RT1, RT2, corr_pos, score): \"\"\" KRT:", "plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234)", "ax3_2) ax3_2.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_3d,", "- depth.min()) / (depth.max() - depth.min()) #######vis fig = plt.figure(1) ax1_1 = fig.add_subplot(331)", "plot_hand_3d(can_3dpoints, visibility, ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera", "ax3.imshow(heatmap_pred.sum(0).T) else: total += 1 visibility = visibility.squeeze()[..., None] can_3dpoints = can_3dpoints *", "de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]),", "ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5", "ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(normed_pred, visibility,", "self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _,", "ax2_1) ax2_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view plot_hand_3d(can_pred,", "self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz line self.ly = sample_ax.axvline(color='k')", "= inputs.get('RT')[0] image_path = inputs.get('img-path') print('image path:', image_path) img = resize(plt.imread(image_path), (128, 84,", "= Circle((xx, yy),2,color='r') self.axs[1, 0].add_patch(circ) plt.show() class Cursor_for_corrspondence(object): def __init__(self, sample_ax, draw_ax, depth,", "pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap", "ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) # ax3.set_zlim([-3, 3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0)", "event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) pr_cost_volume = self.depth[:, int(y), int(x)] cost_volume_xs = np.arange(0, pr_cost_volume.shape[0])", "'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils import zipreader", "KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0])", "0, :, :] * 0.229 + 0.485 img[..., 1, :, :] = img[...,", "cfg.VIS.POINTCLOUD and 'h36m' not in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions", "triangulate from vision.multiview import pix2coord, coord2pix from core import cfg from vision.multiview import", "max_threshold print('AUC: ', auc_value) plt.plot(thresholds, pck, 'r') plt.axis([0, 20, 0, 1]) plt.savefig(auc_path) plt.show()", "for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in", "self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2) inty, intx = int(y+0.5), int(x+0.5) print(self.sample_locs[:,", "depth = np.log(depth) depth = (depth - depth.min()) / (depth.max() - depth.min()) #######vis", "/ p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt += 1 p3D /=", "# ipv.show() if cfg.VIS.POINTCLOUD and 'h36m' in cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names =", "print('intersections', intersections.view(-1, 64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0,", "= inputs.get('other_RT')[0] other_image_path = inputs.get('other_img_path')[0] print('other image path', other_image_path) other_img = resize(plt.imread(other_image_path), (128,", "'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if 'sample_locs' in pred:", "select_img_point = resized_img2.reshape(fh*fw, 3)[select_pos, :] print(select_pos.shape) print('total pos', sum(select_pos)) p3D = cv2.triangulatePoints(KRT2, KRT1,", "pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT, RT, other_RT, corr_pos_pred,", "inputs.get('points-3d') rot_mat = inputs.get('rotation') R_global = inputs.get('R') keypoint_scale = inputs.get('scale') visibility = inputs.get('visibility')", "aligns the 3d coord with the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3,", "3)) heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth')", "visibility delta = normed_pred - normed_3d print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2", "other_img = inputs.get('other_img') heatmap_pred = pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim", "2, 2)[0, inty, intx]) print('start', start.view(-1, 64, 64, 2)[0, inty, intx]) print('vec', vec.view(-1,", "ax3_3) ax3_3.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the camera view #", "4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1,", "feat_h x feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128 x = np.arange(0,", "= inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d = inputs.get('normed-points-3d') target_global =", "sample_ax.axvline(color='k') # the vert line # text location in axes coords self.txt =", "va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H =", "W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1", "return output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\"))", "3d coord with the camera view # ax3.set_xlim([-3, 3]) # ax3.set_ylim([-3, 3]) #", "= sample_locs[i][int(y)][int(x)] depos = de_normalize(pos, H, W) circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) axs[1,", "= cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) pck =", "corr_pos: feat_h x feat_w x 2 score: sample_size x feat_h x feat_w \"\"\"", "self.W = W self.axs = axs self.img2 = img2 self.outs = outs def", "\"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt = 0 # for inputs, pred in", "= (w - w.min()) / (w.max() - w.min()) ax1_1 = fig.add_subplot(335) ax1_1.imshow(w) #", "0, '', va=\"bottom\", ha=\"left\") self.depth = depth self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs", "= pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x,", "True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap =", "im = plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig =", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4] outs = debugmodel(input_img, input_other_img, KRT0, KRT1) H, W = input_img.shape[-2:] print(H,", "inputs.get('camera') other_camera = inputs.get('other_camera') image_path = inputs.get('img-path')[0] print(image_path) # image_path = 'images.zip@' image_file", "plt.imread(image_path) image = np.array(im, dtype=np.int) if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1", "is_train=False, force_shuffle=True)[0] # for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not", "outs): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz", "= fig.add_subplot(235) ax1.imshow(orig_img[::-1].transpose((1,2,0))) ax2.imshow(orig_other_img[::-1].transpose((1,2,0))) ax3.imshow(cpu(batchdata['heatmap'])[0][0].sum(0)) ax4.imshow(cpu(batchdata['other_heatmap'])[0][0].sum(0)) # ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0)))", "x = np.arange(0, img1.shape[1]) # 84 grid_x, grid_y = np.meshgrid(x, y) grid_y =", "pred.get('heatmap_pred') score_pred = pred.get('score_pred') corr_pos_pred = pred.get('corr_pos') sim = pred.get('depth') import pdb; pdb.set_trace()", "= data_numpy[:1000] # assert img.shape == (1000, 1000, 3), img.shape img = inputs.get('img')", "cus = Cursor_for_epipolar_line(axs[0,0], [axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :,", "cfg.OUTPUT_DIR: output_dir = cfg.OUTPUT_DIR dataset_names = cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\"))", "= axs self.img2 = img2 self.outs = outs def mouse_down(self, event): if not", "y) grid_y = pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x", "####### end vis # w = select_img_point[:, :10000].reshape(-1, 100, 100).transpose(1,2,0) # w =", "4076 grid_corr = pix2coord(corr_pos, cfg.BACKBONE.DOWNSAMPLE) grid_corr = grid_corr * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid", "= cfg.DATASETS.TEST predictions = torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) print(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"predictions.pth\")) cnt", "from .ipv_vis import * from vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix", "= np.arange(0, pr_cost_volume.shape[0]) xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f depth=%.5f\\nCorr xx=%d, yy=%d' %", "grid) # depth = np.ones((fh, fw)) * np.min((KRT1@p3D)[2, :]) depth = np.ones((fh, fw))", "corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs, 'camera': camera, 'other_camera': other_camera, } if", ":, :] = img[..., 0, :, :] * 0.229 + 0.485 img[..., 1,", "sample_locs = pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open('baseline_'", ".ipv_vis import * from vision.triangulation import triangulate from vision.multiview import pix2coord, coord2pix from", "0.02 print('->', np.sum(select_pos1)) select_pos2 = np.sum(resized_img2, axis=2) > 20 print('->',np.sum(select_pos2)) select_pos3 = np.sum(corr_pos,", "projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3 = fig.add_subplot(336, projection='3d') ax3_1 = fig.add_subplot(337, projection='3d')", "the vert line # text location in axes coords self.txt = sample_ax.text(0, 0,", "# 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path': other_image_file, #", "ax5.imshow(cpu(outs[0])[0].sum(0)) print(out.shape) out_img = de_transform(cpu(out)[0, ::-1].transpose((1,2,0))) ax5.imshow(out_img) plt.show() else: print(sample_locs.shape) # 64 x", "heatmapat(x, y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap", "debugsample_locs[i, 0, inty, intx].cpu().numpy().copy() depos = de_normalize(pos, self.H, self.W) # circ = Circle((int(depos[0]),", "p = p_homo / p_homo[2] depth[int(coord2pix(p[1], 32)), int(coord2pix(p[0], 32))] = p_homo[2] cnt +=", "self.draw_ax[3].imshow(heatmap, cmap=cmap.hot) self.draw_ax[3].set_title(\"%f~%f\" % (a, b)) # fig.colorbar(im2, ax=axs[0, 1]) circ = Circle((x,", "# pr_cost_volume = self.depth[:, int(y), int(x)] # cost_volume_xs = np.arange(0, pr_cost_volume.shape[0]) # xx,", "0, :, fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, ::4])[0][0]) fig = plt.figure(1) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232)", "0.456 img[..., 2, :, :] = img[..., 2, :, :] * 0.225 +", "w = select_pos.reshape(fh,fw) # w = (w - w.min()) / (w.max() - w.min())", "self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw()", "y, weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap =", "3d coord with the camera view plot_hand_3d(can_3dpoints, visibility, ax2_3) plot_hand_3d(can_pred, visibility, ax2_3) ax2_3.view_init(azim=-90.0,", "pred in predictions: heatmap = inputs.get('heatmap') points2d = inputs.get('points-2d') hand_side = inputs.get('hand-side') img", "64, 64, 4, 2)[0, inty, intx]) print('mask', mask.view(-1, 64, 64, 4)[0, inty, intx])", "| cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape == (1000, 1000, 3),", "w.min()) ax2_1 = fig.add_subplot(339) ax2_1.imshow(w) ####### end vis # w = select_img_point[:, :10000].reshape(-1,", "[axs[0,1], axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs)", "= torch.load(os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"pck.pth\")) if cfg.VIS.AUC: auc_path = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\")", "image_path = 'images.zip@' image_file = osp.join(\"datasets\", 'h36m', 'images.zip@', 'images', image_path) # from utils", "y = event.xdata, event.ydata self.lx.set_ydata(y) self.ly.set_xdata(x) # pr_cost_volume = self.depth[:, int(y), int(x)] #", "circ = Circle((int(depos[0]), int(depos[1])),1,color='b', alpha=0.5) circ = Circle((depos[0], depos[1]), 1 , color='b', alpha=0.5)", "/ (w2.max() - w2.min()) # W = np.stack([w1, w2, np.ones(w2.shape)], axis=0) # ax2_1", "= pred.get('depth') import pdb; pdb.set_trace() # p3D, img_pt = get_point_cloud(img, other_img, KRT, other_KRT,", "3]) plot_hand_3d(normed_3d, visibility, ax3_1) ax3_1.view_init(azim=-90.0, elev=-90.0) # aligns the 3d coord with the", "def __init__(self, sample_ax, draw_ax, depth, corr_pos_pred, sample_locs, H, W): self.sample_ax = sample_ax self.draw_ax", "(1000, 1000, 3), img.shape img = inputs.get('img') other_KRT = inputs.get('other_KRT')[0] # other_RT =", "total = 0 for inputs, pred in predictions: heatmap = inputs.get('heatmap') points2d =", "print(delta) print('L1 err = ', np.abs(delta).sum()) print('L2 err = ', ((delta**2).sum(-1)**0.5).mean()) fig =", "from scipy.misc import imresize sample_size, fh, fw = score.shape resized_img2 = imresize(img2, (fh,", "= inputs.get('points-2d') hand_side = inputs.get('hand-side') img = inputs.get('img') can_3dpoints = inputs.get('can-points-3d') normed_3d =", "weights[1]) im2= self.draw_ax[2].imshow(heatmap, cmap=cmap.hot) self.draw_ax[2].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x,", "# xx, yy = self.corr_pos_pred[int(y)][int(x)] self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i", "= can_pred * visibility normed_3d = normed_3d * visibility normed_pred = normed_pred *", "= batchdata['other_KRT'].squeeze()[None, 0] # batchdata['img']: 1 x 4 x 3 x 256 x", "input_other_img, KRT0, KRT1, outs[2][0]) if not cfg.VIS.CURSOR: # show_img = de_transform(cpu(batchdata['img'][:, 0, :,", "y, np.max(pr_cost_volume), xx, yy)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear()", "pred.get('sample_locs') output['sample_locs'] = sample_locs else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name,", "output['depth'] # corr_pos_pred = output['corr_pos_pred'] # sample_locs = output['sample_locs'] if cfg.EPIPOLAR.VIS: if 'h36m'", "x feat_w \"\"\" y = np.arange(0, img1.shape[0]) # 128 x = np.arange(0, img1.shape[1])", "for idx, batchdata in enumerate(tqdm(data_loader)): if not cfg.VIS.MULTIVIEWH36M and not cfg.VIS.H36M: cpu =", "heatmapat(x, y, weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap", "i in self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64):", "(w1 - w1.min()) / (w1.max() - w1.min()) # w2 = corr_pos[:, :, 1]", "(x, y)) self.sample_ax.figure.canvas.draw() for i in self.draw_ax: i.clear() i.figure.canvas.draw() self.axs[1, 0].clear() self.axs[1, 0].imshow(self.img2)", "sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0, 0].imshow(cpu(input_img)[0, :,", "fig.add_subplot(333) #ax2 = fig.add_subplot(222) ax2_1 = fig.add_subplot(334, projection='3d') ax2_2 = fig.add_subplot(335, projection='3d') ax2_3", "cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # img = data_numpy[:1000] # assert img.shape == (1000, 1000,", "self.corr_pos_pred = corr_pos_pred self.sample_locs = sample_locs self.H = H self.W = W def", "= os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_names[0], \"auc.png\") draw_auc(predictions, pck, auc_path) total = 0 for inputs,", "'h36m' in cfg.OUTPUT_DIR: from data.build import make_data_loader if cfg.VIS.MULTIVIEWH36M: data_loader = make_data_loader(cfg, is_train=True,", "W): self.sample_ax = sample_ax self.draw_ax = draw_ax self.lx = sample_ax.axhline(color='k') # the horiz", "path', other_image_path) other_img = resize(plt.imread(other_image_path), (128, 84, 3)) heatmap_pred = pred.get('heatmap_pred') score_pred =", "4)[0, inty, intx]) print('valid_intersections', valid_intersections.view(-1, 64, 64, 2, 2)[0, inty, intx]) print('start', start.view(-1,", "self.draw_ax: i.clear() i.figure.canvas.draw() axs[1, 0].clear() axs[1, 0].imshow(img2) for i in range(64): pos =", "= (w - w.min()) / (w.max() - w.min()) ax2_1 = fig.add_subplot(338) ax2_1.imshow(w) w", "axs[1,0], axs[1,1]], sample_locs, H, W, axs, \\ cpu(input_other_img)[0, :, :, :][::-1].transpose((1,2,0)), outs) axs[0,", "= fig.add_subplot(326) # ax2_1.imshow(w) plt.show() return p3D, select_img_point def visualization(cfg): if cfg.VIS.POINTCLOUD and", "= int(y+0.5), int(x+0.5) print(self.sample_locs[:, inty, intx]) _, _, _, debugsample_locs, intersections, mask, valid_intersections,", "while True: inputs, pred = predictions[cnt] print('input keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap", ":]) cnt = 0 for i in range(fh): for j in range(fw): if", "else: print('No sample_locs!!!!!') import pickle with open(cfg.OUTPUT_DIR + \"/visualizations/h36m/output{}_{:d}.pkl\".format(name, cnt),\"wb\") as f: pickle.dump(output,f)", "weights[0]) im1= self.draw_ax[1].imshow(heatmap, cmap=cmap.hot) self.draw_ax[1].set_title(\"%f~%f\" % (a, b)) a, b, heatmap = heatmapat(x,", "batchdata['heatmap'][:, 1], batchdata['KRT'][:, 0], batchdata['other_KRT'][:, 1]) out, sample_locs = imgmodel.imgforward_withdepth(input_img, input_other_img, KRT0, KRT1,", "input_img.shape[-2:] print(H, W) orig_img = de_transform(cpu(batchdata['img'].squeeze()[None, ...])[0][0]) orig_other_img = de_transform(cpu(batchdata['other_img'].squeeze()[None, ...])[0][0]) # outs", "/= p3D[3] p3D = p3D[:3].squeeze() depth = (depth - depth.min()) / (depth.max() -", "'p3D': p3D, # 'img_pt': img_pt, 'img1': img, 'img2' : other_img, 'img1_path': image_file, 'img2_path':", "sample_ax.text(0, 0, '', va=\"bottom\", ha=\"left\") def mouse_down(self, event): if not event.inaxes: return x,", "plt.figure(1) ax1_1 = fig.add_subplot(331) ax1_2 = fig.add_subplot(332) #ax1_3 = fig.add_subplot(333) #ax2 = fig.add_subplot(222)", "keys:') print(inputs.keys()) print('pred keys:') print(pred.keys()) heatmap = inputs.get('heatmap') other_heatmap = inputs.get('other_heatmap') points2d =", "np.ones(w2.shape)], axis=0) # ax2_1 = fig.add_subplot(336) # ax2_1.imshow(W.transpose(1,2,0)) ax1_1 = fig.add_subplot(336) ax1_1.imshow(depth) w", "pix2coord(grid_y, cfg.BACKBONE.DOWNSAMPLE) grid_y = grid_y * cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid_x = pix2coord(grid_x, cfg.BACKBONE.DOWNSAMPLE)", "the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.1f, y=%1.1f' % (x, y)) self.sample_ax.figure.canvas.draw() for i", "if cfg.DATASETS.TASK == 'keypoint': fig = plt.figure(1) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332)", "heatmap, 'other_heatmap': other_heatmap, 'points-2d': points2d, 'corr_pos_pred': corr_pos_pred, 'depth': sim, 'heatmap_pred': heatmap_pred, 'batch_locs': batch_locs,", "* cfg.DATASETS.IMAGE_RESIZE * cfg.DATASETS.PREDICT_RESIZE grid = np.stack((grid_x, grid_y)) grid = grid.reshape(2, -1) grid_corr" ]
[ "required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp():", "instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to", "from treadmill import context from treadmill import cli from treadmill import exc import", "hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2", "instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy", "help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def", "callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname',", "init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile',", "instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client =", "master = next( master for master in masters if master['hostname'] == hostname )", "= ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not", "master in masters if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not found", "type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname,", "== hostname ] if not masters: cli.bad_exit('%s not found in the cell config',", "image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell", "\"\"\"Admin module to manage cell ZooKeeper servers. \"\"\" from __future__ import absolute_import from", "treadmill import admin from treadmill import context from treadmill import cli from treadmill", "__future__ import print_function from __future__ import unicode_literals import logging import click from treadmill", "import cli from treadmill import exc import treadmill_aws from treadmill_aws import awscontext from", "try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname'])", "treadmill import exc import treadmill_aws from treadmill_aws import awscontext from treadmill_aws import ec2client", "create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image')", "ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters =", "_LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname])", "profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)')", "envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN',", "module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True,", "is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname", "help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image,", "ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does", "from treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init():", "ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk", "the cell config', hostname) for master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn,", "@click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate')", "@click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs',", "instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname", "manage cell ZooKeeper servers. \"\"\" from __future__ import absolute_import from __future__ import division", "ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk(", "@click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type',", "ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters", "if not masters: cli.bad_exit('%s not found in the cell config', hostname) for master", "for master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2", "@click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False)", "if hostname: masters = [ master for master in masters if master['hostname'] ==", "Copy subnet, type and image from the old instance unless we override. hostmanager.create_zk(", "exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s',", "rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image',", "cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2", "cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters", "ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True,", "hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or", "@click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet,", "config', hostname) for master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] )", "from __future__ import division from __future__ import print_function from __future__ import unicode_literals import", "awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname:", "masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for master in masters", "we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile,", "for master in masters if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not", "expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False)", "help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk", "master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not found in the cell config',", "default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage", "envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type')", "cell ZooKeeper servers. \"\"\" from __future__ import absolute_import from __future__ import division from", "__future__ import division from __future__ import print_function from __future__ import unicode_literals import logging", "found in the cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] )", "size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell", "required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False,", "= [ master for master in masters if master['hostname'] == hostname ] if", "in masters if master['hostname'] == hostname ] if not masters: cli.bad_exit('%s not found", "def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False)", "in the cell config', hostname) for master in masters: try: ec2_instance = ec2client.get_instance(", "= ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except", "ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname)", "_LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk )", "StopIteration: cli.bad_exit('%s not found in the cell config', hostname) try: ec2_instance = ec2client.get_instance(", "absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals", "logging import click from treadmill import admin from treadmill import context from treadmill", "dirty=True)['masters'] if hostname: masters = [ master for master in masters if master['hostname']", "def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create')", "@click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk',", "does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet,", "required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance", ") except StopIteration: cli.bad_exit('%s not found in the cell config', hostname) try: ec2_instance", "not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type", "import division from __future__ import print_function from __future__ import unicode_literals import logging import", "required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image')", "instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client =", "instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client", "is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True,", "admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for master in masters if master['hostname']", "@click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk):", "awscontext from treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def", "cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError:", "the cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except", ") cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client,", "cli.bad_exit('%s not found in the cell config', hostname) for master in masters: try:", "hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn,", "def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn", "ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters']", "server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell,", "cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master,", "in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already", "not masters: cli.bad_exit('%s not found in the cell config', hostname) for master in", "@click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def", "import context from treadmill import cli from treadmill import exc import treadmill_aws from", "masters if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not found in the", "@click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile,", "callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell", "click from treadmill import admin from treadmill import context from treadmill import cli", "instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell,", "and image from the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master,", "required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False,", "for master in masters if master['hostname'] == hostname ] if not masters: cli.bad_exit('%s", "= admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for master in masters if", "server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell,", "already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile,", "subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient", "@click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk):", "@click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet',", "expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to", "from the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or", "logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True,", "help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def", "from treadmill import admin from treadmill import context from treadmill import cli from", "CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt,", "print_function from __future__ import unicode_literals import logging import click from treadmill import admin", "instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del", "import ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell", "@click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet,", "import click from treadmill import admin from treadmill import context from treadmill import", "cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters", "@click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile,", "hostname) # Copy subnet, type and image from the old instance unless we", "@click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell',", "import awscontext from treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__)", "disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell =", "admin from treadmill import context from treadmill import cli from treadmill import exc", "module to manage cell ZooKeeper servers. \"\"\" from __future__ import absolute_import from __future__", "hostname ] if not masters: cli.bad_exit('%s not found in the cell config', hostname)", "old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type", "servers. \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import", "help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet')", "\"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2", "@zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\"", "%s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance", "@zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\"", ") _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client,", "hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2", "found in the cell config', hostname) for master in masters: try: ec2_instance =", "admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for", "except StopIteration: cli.bad_exit('%s not found in the cell config', hostname) try: ec2_instance =", "master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance", "master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile')", "if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not found in the cell", "cell config', hostname) for master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']]", "import exc import treadmill_aws from treadmill_aws import awscontext from treadmill_aws import ec2client from", "= admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master for", "] if not masters: cli.bad_exit('%s not found in the cell config', hostname) for", "except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted:", "ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'],", "master in masters if master['hostname'] == hostname ] if not masters: cli.bad_exit('%s not", "help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create", "hostname: masters = [ master for master in masters if master['hostname'] == hostname", "or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s',", "image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell", "from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\"", "ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile')", "exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image,", "treadmill_aws import awscontext from treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER =", "ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type and image from the", "== hostname ) except StopIteration: cli.bad_exit('%s not found in the cell config', hostname)", "expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\"", "cli from treadmill import exc import treadmill_aws from treadmill_aws import awscontext from treadmill_aws", "<filename>lib/python/treadmill_aws/cli/admin/cell/zk.py<gh_stars>1-10 \"\"\"Admin module to manage cell ZooKeeper servers. \"\"\" from __future__ import absolute_import", "instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell,", "[hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type and image from the old", "instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type,", "not found in the cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname]", "ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist', hostname)", "envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance", "required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True,", "= admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for master", "admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master for master in masters if", "\"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn)", "import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region',", "ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI", "hostname) for master in masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s", "hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type and image from", "subnet, type and image from the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn,", "master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk )", "instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del create_cmd del rotate_cmd", "in masters if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s not found in", "try: master = next( master for master in masters if master['hostname'] == hostname", "import print_function from __future__ import unicode_literals import logging import click from treadmill import", "def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn", "override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image", "division from __future__ import print_function from __future__ import unicode_literals import logging import click", "cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance", "masters: cli.bad_exit('%s not found in the cell config', hostname) for master in masters:", "awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [", "admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master for master", "(G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper", "= awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next(", "instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client", "help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image,", "help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type,", "envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL')", "create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn =", "dirty=True)['masters'] try: master = next( master for master in masters if master['hostname'] ==", "hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type and image", "exc import treadmill_aws from treadmill_aws import awscontext from treadmill_aws import ec2client from treadmill_aws", "masters: try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists',", "ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del create_cmd del", "masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master for master in", "ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master =", "to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image',", "callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt,", "envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt',", "= logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt,", "image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate',", "ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters =", ") cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile',", "admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master", "try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance", "EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) #", "in the cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance)", "from __future__ import unicode_literals import logging import click from treadmill import admin from", "or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del create_cmd", "masters if master['hostname'] == hostname ] if not masters: cli.bad_exit('%s not found in", "hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname'])", "master['hostname'] == hostname ] if not masters: cli.bad_exit('%s not found in the cell", "image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del create_cmd del rotate_cmd return", "from treadmill import exc import treadmill_aws from treadmill_aws import awscontext from treadmill_aws import", "master for master in masters if master['hostname'] == hostname ] if not masters:", "@click.option('--aws-profile', required=False, envvar='AWS_PROFILE', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain',", "ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s EC2 instance does not exist',", "= next( master for master in masters if master['hostname'] == hostname ) except", "type and image from the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client,", "(G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper", "# Copy subnet, type and image from the old instance unless we override.", "subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'], instance_profile=instance_profile, image_id=image or ec2_instance['ImageId'], disk=disk ) cli.out('Created:", "Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False, envvar='AWS_PROFILE',", "if master['hostname'] == hostname ] if not masters: cli.bad_exit('%s not found in the", "subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient", "required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2", "disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to rotate', required=True)", "exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname) # Copy subnet, type and", "\"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--aws-profile', required=False,", "treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk')", "import treadmill_aws from treadmill_aws import awscontext from treadmill_aws import ec2client from treadmill_aws import", "zk_grp(): \"\"\"Manage cell ZooKeeper servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile',", "[ master for master in masters if master['hostname'] == hostname ] if not", "import logging import click from treadmill import admin from treadmill import context from", "@click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2", "hostname ) except StopIteration: cli.bad_exit('%s not found in the cell config', hostname) try:", "EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet,", "awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next( master", "help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet',", "type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname,", "master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL')", "from __future__ import absolute_import from __future__ import division from __future__ import print_function from", "not found in the cell config', hostname) for master in masters: try: ec2_instance", "is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True,", "__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__", "cli.bad_exit('%s EC2 instance does not exist', hostname) hostmanager.delete_hosts(ec2_conn, ipa_client, [hostname]) cli.out('Deleted: %s', hostname)", "ZooKeeper servers. \"\"\" from __future__ import absolute_import from __future__ import division from __future__", "import admin from treadmill import context from treadmill import cli from treadmill import", "callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt,", "to manage cell ZooKeeper servers. \"\"\" from __future__ import absolute_import from __future__ import", "admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master = next( master for master in", "image from the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet", "cli.bad_exit('%s not found in the cell config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn,", "from __future__ import print_function from __future__ import unicode_literals import logging import click from", "import unicode_literals import logging import click from treadmill import admin from treadmill import", "master for master in masters if master['hostname'] == hostname ) except StopIteration: cli.bad_exit('%s", "treadmill_aws from treadmill_aws import awscontext from treadmill_aws import ec2client from treadmill_aws import hostmanager", "to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet')", "except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created:", "%s', hostname) # Copy subnet, type and image from the old instance unless", "context from treadmill import cli from treadmill import exc import treadmill_aws from treadmill_aws", "@click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create')", "_LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False, envvar='AWS_REGION',", "ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance)", "\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function", "instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or", "unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'], instance_type=instance_type or ec2_instance['InstanceType'],", "exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s',", "= awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try:", "= awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if hostname: masters =", "treadmill import context from treadmill import cli from treadmill import exc import treadmill_aws", "from treadmill import cli from treadmill import exc import treadmill_aws from treadmill_aws import", "cli.out('Deleted: %s', hostname) # Copy subnet, type and image from the old instance", "disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell =", "config', hostname) try: ec2_instance = ec2client.get_instance( ec2_conn, hostnames=[hostname] ) _LOGGER.debug(ec2_instance) except exc.NotFoundError: cli.bad_exit('%s", "ec2client.get_instance( ec2_conn, hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError:", "master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk", "help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type,", "@click.option('--hostname', help='Hostname to rotate', required=True) @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type', help='EC2 instance type')", "the old instance unless we override. hostmanager.create_zk( ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet or ec2_instance['SubnetId'],", "subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname',", "= admin_cell.get(cell, dirty=True)['masters'] if hostname: masters = [ master for master in masters", "or ec2_instance['ImageId'], disk=disk ) cli.out('Created: %s', hostname) del create_cmd del rotate_cmd return zk_grp", "__future__ import unicode_literals import logging import click from treadmill import admin from treadmill", "hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell ZooKeeper server(s).\"\"\" ec2_conn = awscontext.GLOBAL.ec2", "from treadmill_aws import awscontext from treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER", "expose_value=False) @click.option('--ipa-certs', required=False, default='/etc/ipa/ca.crt', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False)", "next( master for master in masters if master['hostname'] == hostname ) except StopIteration:", "is_eager=True, expose_value=False) @click.option('--ipa-domain', required=False, envvar='IPA_DOMAIN', callback=treadmill_aws.cli.handle_context_opt, is_eager=True, expose_value=False) def zk_grp(): \"\"\"Manage cell ZooKeeper", "= awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] if", "hostnames=[master['hostname']] ) cli.out('%s EC2 instance already exists', master['hostname']) _LOGGER.debug(ec2_instance) except exc.NotFoundError: hostmanager.create_zk( ec2_conn=ec2_conn,", "hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin Cell CLI module\"\"\" @click.group(name='zk') @click.option('--aws-region', required=False,", "unicode_literals import logging import click from treadmill import admin from treadmill import context", "rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn =", "treadmill_aws import ec2client from treadmill_aws import hostmanager _LOGGER = logging.getLogger(__name__) def init(): \"\"\"Admin", "help='Disk size (G)') @zk_grp.command(name='rotate') def rotate_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Rotate", "masters = [ master for master in masters if master['hostname'] == hostname ]", "ec2_conn=ec2_conn, ipa_client=ipa_client, master=master, subnet_id=subnet, instance_type=instance_type, instance_profile=instance_profile, image_id=image, disk=disk ) cli.out('Created: %s', master['hostname']) @click.option('--cell',", "import absolute_import from __future__ import division from __future__ import print_function from __future__ import", "instance profile') @click.option('--instance-type', help='EC2 instance type') @click.option('--subnet', help='Subnet') @click.option('--image', help='Image') @click.option('--disk', help='Disk size", "treadmill import cli from treadmill import exc import treadmill_aws from treadmill_aws import awscontext", "size (G)') @zk_grp.command(name='create') def create_cmd(cell, hostname, instance_profile, instance_type, subnet, image, disk): \"\"\"Create cell", "awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn) masters = admin_cell.get(cell, dirty=True)['masters'] try: master", "\"\"\"Rotate cell ZooKeeper server.\"\"\" ec2_conn = awscontext.GLOBAL.ec2 ipa_client = awscontext.GLOBAL.ipaclient admin_cell = admin.Cell(context.GLOBAL.ldap.conn)", "servers.\"\"\" @click.option('--cell', required=True, envvar='TREADMILL_CELL') @click.option('--hostname', help='Hostname to create') @click.option('--instance-profile', help='EC2 instance profile') @click.option('--instance-type'," ]
[ "properties self.api_url = api_url self.api_key = api_key # set item validation properties self.forbidden_names", "close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item", "# set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def", "# get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") #", "closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\") item.validate(self.forbidden_names, self.accepted_volumes)", "opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed,", "accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting()", "self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting()", "api_key, forbidden_names, accepted_volumes): # set api properties self.api_url = api_url self.api_key = api_key", "logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider", "accepted_volumes): # set api properties self.api_url = api_url self.api_key = api_key # set", "logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api properties", "__init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api properties self.api_url = api_url self.api_key", "self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item,", "= api_key # set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes", "api_key # set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod", "settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names,", "logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set", "<reponame>nl-hugo/grapy # -*- coding: utf-8 -*- import logging from vendors.exporters import RestApiExporter logger", "vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names,", "api_url self.api_key = api_key # set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes", "api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\")", "from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings", "item validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler):", "crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes =", "RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): #", "set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls,", "from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key,", "api_url, api_key, forbidden_names, accepted_volumes): # set api properties self.api_url = api_url self.api_key =", "forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): # get api settings from", "def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api properties self.api_url = api_url", "import logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self,", "forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self,", "open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self,", "utf-8 -*- import logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object):", "def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def", "= logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api", "crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider", "self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): # get api", "get item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return", "api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url,", "= forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): # get api settings", "cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter =", "= RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def", "= api_url self.api_key = api_key # set item validation properties self.forbidden_names = forbidden_names", "def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing", "forbidden_names, accepted_volumes): # set api properties self.api_url = api_url self.api_key = api_key #", "WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api properties self.api_url =", "properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): # get", "import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes):", "# -*- coding: utf-8 -*- import logging from vendors.exporters import RestApiExporter logger =", "api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item", "-*- import logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def", "logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\") item.validate(self.forbidden_names,", "self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider):", "from_crawler(cls, crawler): # get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key =", "coding: utf-8 -*- import logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class", "api properties self.api_url = api_url self.api_key = api_key # set item validation properties", "RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self,", "-*- coding: utf-8 -*- import logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__)", "def from_crawler(cls, crawler): # get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key", "spider): logger.info(\"Spider closed, close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\")", "@classmethod def from_crawler(cls, crawler): # get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\")", "exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close exporter\")", "api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py", "accepted_volumes @classmethod def from_crawler(cls, crawler): # get api settings from settings.py api_url =", "= accepted_volumes @classmethod def from_crawler(cls, crawler): # get api settings from settings.py api_url", "close exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\") item.validate(self.forbidden_names, self.accepted_volumes) self.exporter.export_item(item)", "crawler): # get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\")", "validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key,", "crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py forbidden_names =", "get api settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get", "self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): # get api settings from settings.py", "exporter\") self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\") item.validate(self.forbidden_names, self.accepted_volumes) self.exporter.export_item(item) return", "return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter", "self.exporter.finish_exporting() def process_item(self, item, spider): logger.info(f\"Processing item {item}\") item.validate(self.forbidden_names, self.accepted_volumes) self.exporter.export_item(item) return item", "crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\")", "open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider): logger.info(\"Spider closed, close", "validation properties self.forbidden_names = forbidden_names self.accepted_volumes = accepted_volumes @classmethod def from_crawler(cls, crawler): #", "= crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes", "# set api properties self.api_url = api_url self.api_key = api_key # set item", "forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key)", "= crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened, open", "= crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider):", "settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def", "= crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from settings.py forbidden_names", "set api properties self.api_url = api_url self.api_key = api_key # set item validation", "spider): logger.info(\"Spider opened, open exporter\") self.exporter = RestApiExporter(self.api_url, self.api_key) self.exporter.start_exporting() def close_spider(self, spider):", "class WineVendorsPipeline(object): def __init__(self, api_url, api_key, forbidden_names, accepted_volumes): # set api properties self.api_url", "self.api_key = api_key # set item validation properties self.forbidden_names = forbidden_names self.accepted_volumes =", "from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes)", "# get item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\")", "item validation settings from settings.py forbidden_names = crawler.settings.getlist(\"FORBIDDEN_NAMES\") accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url,", "settings from settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation", "settings.py api_url = crawler.settings.get(\"DYNAMODB_ENDPOINT\") api_key = crawler.settings.get(\"DYNAMODB_API_KEY\") # get item validation settings from", "accepted_volumes = crawler.settings.getlist(\"ACCEPTED_VOLUMES\") return cls(api_url, api_key, forbidden_names, accepted_volumes) def open_spider(self, spider): logger.info(\"Spider opened,", "logging from vendors.exporters import RestApiExporter logger = logging.getLogger(__name__) class WineVendorsPipeline(object): def __init__(self, api_url,", "self.api_url = api_url self.api_key = api_key # set item validation properties self.forbidden_names =" ]
[ "have 0 < q < 1, typically, q is set to something like", "or 1000 q is the parameter used in the MinDivLP algorithm. Must have", "q < 1, typically, q is set to something like q = 0.1", "y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0 # Set", "1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small)) x_star =", "q) + epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0,", "via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small is", "y_small, y_large, lambda, q) Parameters are: A_k_small is the[m_small, N] - sized sensing", "data vector of size[m_large, 1] lambda is the regularization paramater (larger values indicated", "denom = np.power(B.T @ y_large, 1 - q) + epsilon f = 1/denom", "y_large, 1 - q) + epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const", "epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const *", "is set to something like q = 0.1 Returns: x_star: an [N, 1]", "better fit to constraints, at the cost potentially higher execution time and may", "to over - fitting if set too large. Typical value is 10000 or", "= sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small)) x_star = x_star /", "np.power(B.T @ y_large, 1 - q) + epsilon f = 1/denom x_star =", "constraints, at the cost potentially higher execution time and may lead to over", "1 - q) + epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const *", "numpy as np from .sparse_nnls import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small,", "size[m_small, 1] y_large is the data vector of size[m_large, 1] lambda is the", "at the cost potentially higher execution time and may lead to over -", "parameter used in the MinDivLP algorithm. Must have 0 < q < 1,", "used in the MinDivLP algorithm. Must have 0 < q < 1, typically,", "sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small)) x_star = x_star / sum(x_star)", "vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic,", "cost potentially higher execution time and may lead to over - fitting if", "1] y_large is the data vector of size[m_large, 1] lambda is the regularization", "N] - sized sensing matrix A_k_large is the[m_large, N] - sized sensing matrix", "Parameters are: A_k_small is the[m_small, N] - sized sensing matrix A_k_large is the[m_large,", "const * A_k_small)), np.append(0, const * y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star", "potentially higher execution time and may lead to over - fitting if set", "const * y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0", "sized sensing matrix A_k_large is the[m_large, N] - sized sensing matrix y_small is", "x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small)) x_star = x_star", "x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small is the[m_small,", "def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized", "const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version of the MinDivLP algorithm.", "the parameter used in the MinDivLP algorithm. Must have 0 < q <", "1000 q is the parameter used in the MinDivLP algorithm. Must have 0", "sensing matrix y_small is the data vector of size[m_small, 1] y_large is the", "indicated better fit to constraints, at the cost potentially higher execution time and", "are: A_k_small is the[m_small, N] - sized sensing matrix A_k_large is the[m_large, N]", "np.append(0, const * y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)] =", "regularization paramater (larger values indicated better fit to constraints, at the cost potentially", "Must have 0 < q < 1, typically, q is set to something", "from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\"", "size[m_large, 1] lambda is the regularization paramater (larger values indicated better fit to", "+ epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const", "is the data vector of size[m_large, 1] lambda is the regularization paramater (larger", "the data vector of size[m_small, 1] y_large is the data vector of size[m_large,", "* y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0 #", "> 0 epsilon = 0.0001 denom = np.power(B.T @ y_large, 1 - q)", "1] vector \"\"\" B = A_k_large > 0 epsilon = 0.0001 denom =", "x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0 # Set threshold return x_star", "import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A", "paramater (larger values indicated better fit to constraints, at the cost potentially higher", ".sparse_nnls import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const,", "A_k_large > 0 epsilon = 0.0001 denom = np.power(B.T @ y_large, 1 -", "value is 10000 or 1000 q is the parameter used in the MinDivLP", "scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP", "vector of size[m_small, 1] y_large is the data vector of size[m_large, 1] lambda", "A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small is the[m_small, N] - sized", "B = A_k_large > 0 epsilon = 0.0001 denom = np.power(B.T @ y_large,", "the MinDivLP algorithm. Must have 0 < q < 1, typically, q is", "time and may lead to over - fitting if set too large. Typical", "epsilon = 0.0001 denom = np.power(B.T @ y_large, 1 - q) + epsilon", "thresh=0.01): \"\"\" MinDivLP A basic, regularized version of the MinDivLP algorithm. Call via:", "regularized version of the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small,", "= MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small is the[m_small, N]", "is the[m_small, N] - sized sensing matrix A_k_large is the[m_large, N] - sized", "y_small is the data vector of size[m_small, 1] y_large is the data vector", "[N, 1] vector \"\"\" B = A_k_large > 0 epsilon = 0.0001 denom", "import numpy as np from .sparse_nnls import sparse_nnls from scipy.sparse import vstack def", "like q = 0.1 Returns: x_star: an [N, 1] vector \"\"\" B =", "the[m_small, N] - sized sensing matrix A_k_large is the[m_large, N] - sized sensing", "and may lead to over - fitting if set too large. Typical value", "0 < q < 1, typically, q is set to something like q", "1, typically, q is set to something like q = 0.1 Returns: x_star:", "of size[m_small, 1] y_large is the data vector of size[m_large, 1] lambda is", "of size[m_large, 1] lambda is the regularization paramater (larger values indicated better fit", "of the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda,", "over - fitting if set too large. Typical value is 10000 or 1000", "something like q = 0.1 Returns: x_star: an [N, 1] vector \"\"\" B", "0 epsilon = 0.0001 denom = np.power(B.T @ y_large, 1 - q) +", "q is the parameter used in the MinDivLP algorithm. Must have 0 <", "is the regularization paramater (larger values indicated better fit to constraints, at the", "the data vector of size[m_large, 1] lambda is the regularization paramater (larger values", "large. Typical value is 10000 or 1000 q is the parameter used in", "matrix y_small is the data vector of size[m_small, 1] y_large is the data", "A_k_large is the[m_large, N] - sized sensing matrix y_small is the data vector", "= np.power(B.T @ y_large, 1 - q) + epsilon f = 1/denom x_star", "* A_k_small)), np.append(0, const * y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star <", "execution time and may lead to over - fitting if set too large.", "A_k_small)), np.append(0, const * y_small)) x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)]", "the regularization paramater (larger values indicated better fit to constraints, at the cost", "lambda, q) Parameters are: A_k_small is the[m_small, N] - sized sensing matrix A_k_large", "MinDivLP algorithm. Must have 0 < q < 1, typically, q is set", "is the[m_large, N] - sized sensing matrix y_small is the data vector of", "fitting if set too large. Typical value is 10000 or 1000 q is", "A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version of", "- fitting if set too large. Typical value is 10000 or 1000 q", "to constraints, at the cost potentially higher execution time and may lead to", "basic, regularized version of the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large,", "N] - sized sensing matrix y_small is the data vector of size[m_small, 1]", "< q < 1, typically, q is set to something like q =", "= 0.1 Returns: x_star: an [N, 1] vector \"\"\" B = A_k_large >", "version of the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large,", "y_large, lambda, q) Parameters are: A_k_small is the[m_small, N] - sized sensing matrix", "- sized sensing matrix A_k_large is the[m_large, N] - sized sensing matrix y_small", "set to something like q = 0.1 Returns: x_star: an [N, 1] vector", "in the MinDivLP algorithm. Must have 0 < q < 1, typically, q", "algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are:", "- sized sensing matrix y_small is the data vector of size[m_small, 1] y_large", "1] lambda is the regularization paramater (larger values indicated better fit to constraints,", "@ y_large, 1 - q) + epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T,", "np from .sparse_nnls import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small,", "MinDivLP A basic, regularized version of the MinDivLP algorithm. Call via: x_star =", "Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small", "sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01):", "vector of size[m_large, 1] lambda is the regularization paramater (larger values indicated better", "y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version of the MinDivLP", "the[m_large, N] - sized sensing matrix y_small is the data vector of size[m_small,", "vector \"\"\" B = A_k_large > 0 epsilon = 0.0001 denom = np.power(B.T", "q is set to something like q = 0.1 Returns: x_star: an [N,", "\"\"\" MinDivLP A basic, regularized version of the MinDivLP algorithm. Call via: x_star", "MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters", "= 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small)) x_star", "x_star = x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0 # Set threshold", "sensing matrix A_k_large is the[m_large, N] - sized sensing matrix y_small is the", "is the parameter used in the MinDivLP algorithm. Must have 0 < q", "10000 or 1000 q is the parameter used in the MinDivLP algorithm. Must", "lead to over - fitting if set too large. Typical value is 10000", "q = 0.1 Returns: x_star: an [N, 1] vector \"\"\" B = A_k_large", "< 1, typically, q is set to something like q = 0.1 Returns:", "q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version of the MinDivLP algorithm. Call", "may lead to over - fitting if set too large. Typical value is", "as np from .sparse_nnls import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large,", "is the data vector of size[m_small, 1] y_large is the data vector of", "import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q,", "- q) + epsilon f = 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)),", "x_star: an [N, 1] vector \"\"\" B = A_k_large > 0 epsilon =", "values indicated better fit to constraints, at the cost potentially higher execution time", "0.0001 denom = np.power(B.T @ y_large, 1 - q) + epsilon f =", "MinDivLP(A_k_small, A_k_large, y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version", "fit to constraints, at the cost potentially higher execution time and may lead", "too large. Typical value is 10000 or 1000 q is the parameter used", "if set too large. Typical value is 10000 or 1000 q is the", "y_large is the data vector of size[m_large, 1] lambda is the regularization paramater", "Typical value is 10000 or 1000 q is the parameter used in the", "\"\"\" B = A_k_large > 0 epsilon = 0.0001 denom = np.power(B.T @", "to something like q = 0.1 Returns: x_star: an [N, 1] vector \"\"\"", "typically, q is set to something like q = 0.1 Returns: x_star: an", "0.1 Returns: x_star: an [N, 1] vector \"\"\" B = A_k_large > 0", "= A_k_large > 0 epsilon = 0.0001 denom = np.power(B.T @ y_large, 1", "= 0.0001 denom = np.power(B.T @ y_large, 1 - q) + epsilon f", "data vector of size[m_small, 1] y_large is the data vector of size[m_large, 1]", "sized sensing matrix y_small is the data vector of size[m_small, 1] y_large is", "an [N, 1] vector \"\"\" B = A_k_large > 0 epsilon = 0.0001", "(larger values indicated better fit to constraints, at the cost potentially higher execution", "from .sparse_nnls import sparse_nnls from scipy.sparse import vstack def MinDivLP(A_k_small, A_k_large, y_small, y_large,", "A basic, regularized version of the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small,", "= x_star / sum(x_star) x_star[np.where(x_star < thresh)] = 0 # Set threshold return", "the cost potentially higher execution time and may lead to over - fitting", "matrix A_k_large is the[m_large, N] - sized sensing matrix y_small is the data", "the MinDivLP algorithm. Call via: x_star = MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q)", "A_k_small is the[m_small, N] - sized sensing matrix A_k_large is the[m_large, N] -", "MinDivLP(A_k_small, A_k_large, y_small, y_large, lambda, q) Parameters are: A_k_small is the[m_small, N] -", "higher execution time and may lead to over - fitting if set too", "q) Parameters are: A_k_small is the[m_small, N] - sized sensing matrix A_k_large is", "y_small, y_large, const, q, thresh=0.01): \"\"\" MinDivLP A basic, regularized version of the", "<reponame>KoslickiLab/DiversityOptimization<filename>PythonCode/src/MinDivLP.py import numpy as np from .sparse_nnls import sparse_nnls from scipy.sparse import vstack", "f = 1/denom x_star = sparse_nnls(vstack((f.T, const * A_k_small)), np.append(0, const * y_small))", "lambda is the regularization paramater (larger values indicated better fit to constraints, at", "set too large. Typical value is 10000 or 1000 q is the parameter", "is 10000 or 1000 q is the parameter used in the MinDivLP algorithm.", "algorithm. Must have 0 < q < 1, typically, q is set to", "Returns: x_star: an [N, 1] vector \"\"\" B = A_k_large > 0 epsilon" ]
[ "filename. sequence: The sequence to BLAST. options: Any extra options to pass to", "option_string) extras = [] for o in options: if o[1] not in exclude:", "[], } query_from = [] query_to = [] for hs in ht.findall('.//Hsp'): hsp", "sequence, options): \"\"\" Perform a BLAST search on the given database using the", "A tuple containing the stdout and stderr of the program. # Test: >>>", "class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7", "sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take", "containing a genetic sequence. Returns: An HTML string. \"\"\" formatted = '' for", "found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found = '' return found", "\"\"\" Extract a sequence from the given BLAST database and return it Args:", "filecontents: The contents of a BLAST XML file. cutoff: The cutoff for which", "# Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location':", "'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100", "'-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p", "sequence information. Returns: An HTML string of the formatted sequence. \"\"\" cl =", "%t'\"]) except: found = '' found = [entry.split(' ',2) for entry in re.split(r'\\n',", "> 1] databases = {} for f in found: if f[1].lower() not in", "def chunk_string(s, l=10): \"\"\" Split a string into chunks of a set length.", "string chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate", "ln, line in enumerate(query): query_from = int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl)", "if o[1] not in exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid,", "in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message, stor that for later", "= [] for hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'),", "title of the BLAST database to search for. Returns: The location of the", "parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr =", "program, filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST search on the given", "for ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'),", "XML file. cutoff: The cutoff for which a sequence is considered relevant. Returns:", "BLAST executable. Returns: A tuple containing the stdout and stderr of the program.", "containing the stdout and stderr of the program. # Test: >>> seq =", "\"\"\" try: with open(name) as results: if os.path.getsize(name) > 0: return results.read() raise", "HTML string of the formatted sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'],", "in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'),", "subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr) def", "BLAST executables. db_loc: Directory containing the BLAST DB. Returns: A dict containing lists", "k,l in database_list.iteritems(): flat.extend(l) for d in flat: if title == d['title']: return", "the string chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\"", "output = \"\" for ln, line in enumerate(query): query_from = int(hsp['query_from']) if ln", "Returns: An HTML string. \"\"\" formatted = '' for b in bases: formatted", "'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id':", "tempfile import os from lxml import etree import pprint from math_tools import percentile", "json import re import hashlib import tempfile import os from lxml import etree", "containing lists of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location':", "hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] =", "db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f", "db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in", "(full path). program: The program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The", "math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using in", "options filtering out excluded options Args: option_string: A string containing extra blast options.", "The directory to store the XML output. file_uuid: A unique identifier for the", "'-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db',", "query_to = [] for hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score':", "int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to']))", "the formatted sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl) match =", "import tempfile import os from lxml import etree import pprint from math_tools import", "sequence. Returns: An HTML string. \"\"\" formatted = '' for b in bases:", "query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1)", "import subprocess import base64 import json import re import hashlib import tempfile import", "get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except:", "path). program: The program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory", "[{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd',", "found else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try:", "b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id':", "i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours the bases in", "[] query_to = [] for hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'),", "format_bases(bases): \"\"\" Generate HTML that colours the bases in a string. Args: bases:", "return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title get the", "BLAST XML file. cutoff: The cutoff for which a sequence is considered relevant.", "a give title get the actual name of the database (it may differ", "IOError except IOError: return False def chunk_string(s, l=10): \"\"\" Split a string into", "= subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found = '' found", "\"\"\" Check if the file <name> has been created, indicating BLAST has finished,", "options. exclude: Options to exclude from the generated list. Returns: A list of", "list containing the string chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def", "b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht", "created. \"\"\" try: with open(name) as results: if os.path.getsize(name) > 0: return results.read()", "sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from)", "= chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line in enumerate(query): query_from =", "b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'),", "into a usable dict. Args: filecontents: The contents of a BLAST XML file.", "= t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file", "hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score'])", "cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line in enumerate(query):", "'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue'])", "'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc,", "BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = [] for k,l in", "BLASTX). filestore: The directory to store the XML output. file_uuid: A unique identifier", "the stdout and stderr of the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test", "(e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to store the XML output. file_uuid:", "'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] =", "False if it has not yet been created. \"\"\" try: with open(name) as", "the file <name> has been created, indicating BLAST has finished, and return results", "containing the sequence information. Returns: An HTML string of the formatted sequence. \"\"\"", "using in given path and return a list Args: exe_loc: Location (directory) of", "else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output +=", "ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from", "db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found = '' found = [entry.split(' ',2)", "Look for BLAST databases using in given path and return a list Args:", "in a string. Args: bases: A string containing a genetic sequence. Returns: An", "'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps':", "'-list_outfmt', \"'%f %p %t'\"]) except: found = '' found = [entry.split(' ',2) for", "that colours the bases in a string. Args: bases: A string containing a", "of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = [] for", "which a sequence is considered relevant. Returns: A dict of the results. \"\"\"", "p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check if the file <name> has", "string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db',", "of the database (it may differ from title) Args: exe_loc: Location (directory) of", "available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide':", "into chunks of a set length. Args: s: The string to chunk. l:", "%p %t'\"]) except: found = '' found = [entry.split(' ',2) for entry in", "\"'%f %p %t'\"]) except: found = '' found = [entry.split(' ',2) for entry", "etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'),", "def format_bases(bases): \"\"\" Generate HTML that colours the bases in a string. Args:", "'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to = []", "title: The title of the BLAST database to search for. Returns: The location", "stor that for later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r", "b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] }", "query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output", "a set length. Args: s: The string to chunk. l: The length of", "in options: if o[1] not in exclude: extras.extend(o[1:]) return extras def run_blast(database, program,", "len(entry) > 1] databases = {} for f in found: if f[1].lower() not", "not in exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid, sequence, options):", "results: if os.path.getsize(name) > 0: return results.read() raise IOError except IOError: return False", "hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100", "query = [program, '-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs',", "etree import pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for", "== 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln ==", "b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for", "get. Returns: The sequence if found else an empty string # Test: >>>", "'-db', db, '-entry', seq_id]) except: found = '' return found def parse_extra_options(option_string, exclude=[]):", "'-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra =", "containing the BLAST DB. Returns: A dict containing lists of databases available. #", "database to search for. Returns: The location of the BLAST database. \"\"\" database_list", "path and return a list Args: exe_loc: Location (directory) of the BLAST executables.", "re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in options: if o[1] not", "in a BLAST search. Returns: The file or False if it has not", "Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'),", "'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff:", "created in a BLAST search. Returns: The file or False if it has", "format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject", "import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using in given", "filename of the file that was created in a BLAST search. Returns: The", "0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0", "'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), },", "seq_id]) except: found = '' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an", "ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession':", "None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length':", "and return a list Args: exe_loc: Location (directory) of the BLAST executables. db_loc:", "a genetic sequence. Returns: An HTML string. \"\"\" formatted = '' for b", "search (full path). program: The program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore:", "in flat: if title == d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db,", "seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\"", "Extract a sequence from the given BLAST database and return it Args: exe_loc:", "The filename of the file that was created in a BLAST search. Returns:", "b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]]", "'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for", "Directory containing the BLAST DB. Returns: A dict containing lists of databases available.", "Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry',", "chunks of a set length. Args: s: The string to chunk. l: The", "} for ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def':", "chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line in enumerate(query): query_from = int(hsp['query_from'])", "not yet been created. \"\"\" try: with open(name) as results: if os.path.getsize(name) >", "\"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject", "BLASTN, TBLASTN, BLASTX). filestore: The directory to store the XML output. file_uuid: A", "length of the chunks. Returns: A list containing the string chunks. \"\"\" return", "\"\"\" Generate HTML that colours the bases in a string. Args: bases: A", "found: if f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]})", "f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give", "def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title get the actual name", "the BLAST executables. db_loc: Directory containing the BLAST DB. title: The title of", "\"\"\" results = {'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents) # Get", "60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from)", "extras = [] for o in options: if o[1] not in exclude: extras.extend(o[1:])", "\"\"\" Take a BLAST XML results file and process into a usable dict.", "Returns: A list of options except those in exclude \"\"\" options = re.findall(r'((-\\w+)", "executables. db: The database to get sequence from. seq_id: The sequence ID of", "'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'),", "'-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query,", "unique identifier for the filename. sequence: The sequence to BLAST. options: Any extra", "os from lxml import etree import pprint from math_tools import percentile def get_blast_databases(exe_loc,", "of a set length. Args: s: The string to chunk. l: The length", "qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a", ") return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results file", "Returns: A dict of the results. \"\"\" results = {'results':[], 'messages':[]} messages =", "'-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt',", "BLAST database and return it Args: exe_loc: Directory containing BLAST executables. db: The", "u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0,", "import hashlib import tempfile import os from lxml import etree import pprint from", "TBLASTN, BLASTX). filestore: The directory to store the XML output. file_uuid: A unique", "class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and format it for", "(directory) of the BLAST executables. db_loc: Directory containing the BLAST DB. Returns: A", "of options filtering out excluded options Args: option_string: A string containing extra blast", "get the actual name of the database (it may differ from title) Args:", "'''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001):", "database_list = get_blast_databases(exe_loc, db_loc) flat = [] for k,l in database_list.iteritems(): flat.extend(l) for", "option_string: A string containing extra blast options. exclude: Options to exclude from the", "# Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db,", "'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'),", "information. Returns: An HTML string of the formatted sequence. \"\"\" cl = 60", "'-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude =", "hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) <", "title): \"\"\" For a give title get the actual name of the database", "program: The program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to", "of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title':", "BLAST XML results file and process into a usable dict. Args: filecontents: The", "query Args: database: The database to search (full path). program: The program to", "IOError: return False def chunk_string(s, l=10): \"\"\" Split a string into chunks of", "line in enumerate(query): query_from = int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to", "\"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out', '-subject', '-html', '-gilist',", "'-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name',", "cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60)", "a list Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing", "= format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre", "= '' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options", "def create_formatted_sequences(hsp): \"\"\" Take a sequence and format it for display. Args: hsp:", "== d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a", "hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'),", "exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing the BLAST DB.", "of options except those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras", "Returns: The location of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat", "sequence to BLAST. options: Any extra options to pass to the BLAST executable.", "'-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p =", "has not yet been created. \"\"\" try: with open(name) as results: if os.path.getsize(name)", "b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message, stor that for later use", "exe_loc: Directory containing BLAST executables. db: The database to get sequence from. seq_id:", "',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1] databases", "stdout and stderr of the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\"", "as results: if os.path.getsize(name) > 0: return results.read() raise IOError except IOError: return", "for k,l in database_list.iteritems(): flat.extend(l) for d in flat: if title == d['title']:", "] extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)", "ID of the sequence to get. Returns: The sequence if found else an", "{ 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'),", "of the formatted sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl) match", "extra options to pass to the BLAST executable. Returns: A tuple containing the", "\"\"\" Look for BLAST databases using in given path and return a list", "sseq = format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre>", "and return it Args: exe_loc: Directory containing BLAST executables. db: The database to", "(directory) of the BLAST executables. db_loc: Directory containing the BLAST DB. title: The", "return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours", "re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1] databases = {} for f", "XML results file and process into a usable dict. Args: filecontents: The contents", "'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), }", "hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'),", "chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line in", "h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to'] = max(query_to) r['hits'].append(h) results['results'].append(r) return", "found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found = ''", "{ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre>", "has been created, indicating BLAST has finished, and return results Args: name: The", "dict containing lists of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein':", "and return results Args: name: The filename of the file that was created", "int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output += '''", "BLAST. options: Any extra options to pass to the BLAST executable. Returns: A", "[] for o in options: if o[1] not in exclude: extras.extend(o[1:]) return extras", "hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0:", "'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive':", "file <name> has been created, indicating BLAST has finished, and return results Args:", "'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'),", "dict. Args: filecontents: The contents of a BLAST XML file. cutoff: The cutoff", "HTML that colours the bases in a string. Args: bases: A string containing", "'-entry', seq_id]) except: found = '' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create", "the BLAST DB. title: The title of the BLAST database to search for.", "Location (directory) of the BLAST executables. db_loc: Directory containing the BLAST DB. title:", "the chunks. Returns: A list containing the string chunks. \"\"\" return [s[i:i+l] for", "cutoff for which a sequence is considered relevant. Returns: A dict of the", "'-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out',", "flat = [] for k,l in database_list.iteritems(): flat.extend(l) for d in flat: if", "the given BLAST database and return it Args: exe_loc: Directory containing BLAST executables.", "{'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents) # Get BLAST details db_loc", "databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc,", "'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h", "BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference':", "for o in options: if o[1] not in exclude: extras.extend(o[1:]) return extras def", "formatted = '' for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted", "formatted sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'],", "results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a", "the sequence information. Returns: An HTML string of the formatted sequence. \"\"\" cl", "b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_',", "to exclude from the generated list. Returns: A list of options except those", "False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from the given BLAST", "get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title get the actual name of", "indicating BLAST has finished, and return results Args: name: The filename of the", "A unique identifier for the filename. sequence: The sequence to BLAST. options: Any", "max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to'] = max(query_to) r['hits'].append(h) results['results'].append(r)", "'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in", "\"\"\" For a give title get the actual name of the database (it", "db_loc) flat = [] for k,l in database_list.iteritems(): flat.extend(l) for d in flat:", "options except those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras =", "file. cutoff: The cutoff for which a sequence is considered relevant. Returns: A", "BLAST DB. Returns: A dict containing lists of databases available. # Test it!", "name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The", "b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits':", "class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln],", "seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum}", "subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line in enumerate(query): query_from", "if len(entry) > 1] databases = {} for f in found: if f[1].lower()", "'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] =", "'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h = {", "chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from'] =", "file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist',", "'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1)", "search. Returns: The file or False if it has not yet been created.", "exclude=[]): \"\"\" Create an list of options filtering out excluded options Args: option_string:", "t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in", "= \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query", "string containing extra blast options. exclude: Options to exclude from the generated list.", "\"\"\" formatted = '' for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\"", "get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\"", "Returns: A tuple containing the stdout and stderr of the program. # Test:", "hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'),", "the database (it may differ from title) Args: exe_loc: Location (directory) of the", "dict of the results. \"\"\" results = {'results':[], 'messages':[]} messages = [] b", "containing the BLAST DB. title: The title of the BLAST database to search", "match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\"", "filestore: The directory to store the XML output. file_uuid: A unique identifier for", "Args: hsp: A dict containing the sequence information. Returns: An HTML string of", "The cutoff for which a sequence is considered relevant. Returns: A dict of", "blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>>", "to get sequence from. seq_id: The sequence ID of the sequence to get.", ">>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program,", "def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using in given path and", "give title get the actual name of the database (it may differ from", "stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check", "Args: exe_loc: Directory containing BLAST executables. db: The database to get sequence from.", "def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from the given BLAST database", "of the BLAST executables. db_loc: Directory containing the BLAST DB. Returns: A dict", "to search (full path). program: The program to use (e.g. BLASTN, TBLASTN, BLASTX).", "if f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return", "database using the given query Args: database: The database to search (full path).", "Args: s: The string to chunk. l: The length of the chunks. Returns:", "file that was created in a BLAST search. Returns: The file or False", "Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre>", "60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) >", "output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum}", "False def chunk_string(s, l=10): \"\"\" Split a string into chunks of a set", "hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'),", "in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1] databases = {} for", "Returns: A list containing the string chunks. \"\"\" return [s[i:i+l] for i in", "b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'),", "The file may contain a message, stor that for later use if it.find('.//Iteration_message')", "if len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] =", "in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours the bases in a", "= re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in options: if o[1]", "not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'),", "h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to'] = max(query_to)", "results = {'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents) # Get BLAST", "results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'),", "hsp: A dict containing the sequence information. Returns: An HTML string of the", "database to get sequence from. seq_id: The sequence ID of the sequence to", "= int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] =", "options to pass to the BLAST executable. Returns: A tuple containing the stdout", "a sequence is considered relevant. Returns: A dict of the results. \"\"\" results", "in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'):", "b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): #", "DB. title: The title of the BLAST database to search for. Returns: The", "= subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div class=\"row\">", "has finished, and return results Args: name: The filename of the file that", "= format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query", "to chunk. l: The length of the chunks. Returns: A list containing the", "an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found =", "seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/',", "'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, }", "a sequence and format it for display. Args: hsp: A dict containing the", "= [] for k,l in database_list.iteritems(): flat.extend(l) for d in flat: if title", "return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from", "chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML", "chunk. l: The length of the chunks. Returns: A list containing the string", "the sequence to get. Returns: The sequence if found else an empty string", "\"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found = ''", "string of the formatted sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl)", "found = [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry)", "match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for ln,", "< cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'],", "pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases", "found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd',", "and stderr of the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>>", "exclude = [ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt',", "'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda':", "containing extra blast options. exclude: Options to exclude from the generated list. Returns:", "sequence and format it for display. Args: hsp: A dict containing the sequence", "\"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that", "#float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk']", "'/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db', database,", "with open(name) as results: if os.path.getsize(name) > 0: return results.read() raise IOError except", "file or False if it has not yet been created. \"\"\" try: with", "the results. \"\"\" results = {'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents)", "Args: option_string: A string containing extra blast options. exclude: Options to exclude from", "= { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': {", "{ 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [],", "sequence if found else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|')", "([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in options: if o[1] not in", "executable. Returns: A tuple containing the stdout and stderr of the program. #", "sequence: The sequence to BLAST. options: Any extra options to pass to the", "l: The length of the chunks. Returns: A list containing the string chunks.", "a BLAST XML file. cutoff: The cutoff for which a sequence is considered", "it has not yet been created. \"\"\" try: with open(name) as results: if", "'<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and format it", "cutoff: The cutoff for which a sequence is considered relevant. Returns: A dict", "'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq':", "'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt',", "len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to)", "excluded options Args: option_string: A string containing extra blast options. exclude: Options to", "details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'),", "empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd',", "database (it may differ from title) Args: exe_loc: Location (directory) of the BLAST", "the BLAST DB. Returns: A dict containing lists of databases available. # Test", "\"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in options:", "= { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def':", "enumerate(query): query_from = int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1)", "h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to']", "formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and", "bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'],", "XML output. file_uuid: A unique identifier for the filename. sequence: The sequence to", "An HTML string of the formatted sequence. \"\"\" cl = 60 query =", "hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'),", "= {'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents) # Get BLAST details", "db: The database to get sequence from. seq_id: The sequence ID of the", "[] for k,l in database_list.iteritems(): flat.extend(l) for d in flat: if title ==", "A dict containing the sequence information. Returns: An HTML string of the formatted", "hashlib import tempfile import os from lxml import etree import pprint from math_tools", "'/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list',", "'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params':", "for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1] databases =", "The sequence to BLAST. options: Any extra options to pass to the BLAST", "the filename. sequence: The sequence to BLAST. options: Any extra options to pass", "db, '-entry', seq_id]) except: found = '' return found def parse_extra_options(option_string, exclude=[]): \"\"\"", "'/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt',", "to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to store the XML", "list. Returns: A list of options except those in exclude \"\"\" options =", "extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout,", "results Args: name: The filename of the file that was created in a", "been created. \"\"\" try: with open(name) as results: if os.path.getsize(name) > 0: return", "<pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq}", "format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1", "except IOError: return False def chunk_string(s, l=10): \"\"\" Split a string into chunks", "file and process into a usable dict. Args: filecontents: The contents of a", "</pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def", "return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and format it for display.", "Args: filecontents: The contents of a BLAST XML file. cutoff: The cutoff for", "'', found)) if len(entry) > 1] databases = {} for f in found:", "hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'),", "'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to':", "2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq =", "hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp)", "program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq,", "created, indicating BLAST has finished, and return results Args: name: The filename of", "= subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr)", "[program, '-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude", "if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk']", "int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp)", "return a list Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory", "query_from = int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from", "found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options filtering out excluded", "yet been created. \"\"\" try: with open(name) as results: if os.path.getsize(name) > 0:", "store the XML output. file_uuid: A unique identifier for the filename. sequence: The", "seq_id): \"\"\" Extract a sequence from the given BLAST database and return it", "bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence", "The sequence if found else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt',", "message, stor that for later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else:", "try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found = '' return", "return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options filtering out", "\"\"\" Perform a BLAST search on the given database using the given query", "a sequence from the given BLAST database and return it Args: exe_loc: Directory", "subprocess import base64 import json import re import hashlib import tempfile import os", "the actual name of the database (it may differ from title) Args: exe_loc:", "the given database using the given query Args: database: The database to search", "senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results", "= chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if", "usable dict. Args: filecontents: The contents of a BLAST XML file. cutoff: The", "a BLAST search. Returns: The file or False if it has not yet", "= subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list',", "The title of the BLAST database to search for. Returns: The location of", "display. Args: hsp: A dict containing the sequence information. Returns: An HTML string", "\"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = [] for k,l in database_list.iteritems(): flat.extend(l)", "considered relevant. Returns: A dict of the results. \"\"\" results = {'results':[], 'messages':[]}", "b = etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = {", "given BLAST database and return it Args: exe_loc: Directory containing BLAST executables. db:", "d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence", "> bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] =", "<pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to", "database_list.iteritems(): flat.extend(l) for d in flat: if title == d['title']: return d['location'] return", "== 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln])", "= [] for o in options: if o[1] not in exclude: extras.extend(o[1:]) return", "a message, stor that for later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text)", "= subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found = '' return found def", "A list containing the string chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)]", "A dict of the results. \"\"\" results = {'results':[], 'messages':[]} messages = []", "for the filename. sequence: The sequence to BLAST. options: Any extra options to", "databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title):", "ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to = [] for hs in", "An HTML string. \"\"\" formatted = '' for b in bases: formatted +=", "b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h =", "list Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing the", "for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\"", "{ 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'),", "poll(name): \"\"\" Check if the file <name> has been created, indicating BLAST has", "chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps'])", "'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': []", ">>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id])", "bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check if", "been created, indicating BLAST has finished, and return results Args: name: The filename", "return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from the given", "Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing the BLAST", "seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'})", "Options to exclude from the generated list. Returns: A list of options except", "int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from'])", "db_loc: Directory containing the BLAST DB. Returns: A dict containing lists of databases", "database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [", "The database to search (full path). program: The program to use (e.g. BLASTN,", "b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h = { 'num':", "h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'),", "set length. Args: s: The string to chunk. l: The length of the", "query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60)", "For a give title get the actual name of the database (it may", "sequence from the given BLAST database and return it Args: exe_loc: Directory containing", "subject_from = int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq", "{} for f in found: if f[1].lower() not in databases: databases[f[1].lower()] = []", "options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in options: if", "'-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query',", "'messages':[]} messages = [] b = etree.fromstring(filecontents) # Get BLAST details db_loc =", "= etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program':", "'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found =", "'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'),", "contain a message, stor that for later use if it.find('.//Iteration_message') is not None:", "use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to store the XML output.", "= 60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'],", "may contain a message, stor that for later use if it.find('.//Iteration_message') is not", "+= ''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum}", "given path and return a list Args: exe_loc: Location (directory) of the BLAST", "hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted']", "'-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db',", "qseq = format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre class=\"col-xs-1", "BLAST search. Returns: The file or False if it has not yet been", "db_loc): \"\"\" Look for BLAST databases using in given path and return a", "ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq =", "return it Args: exe_loc: Directory containing BLAST executables. db: The database to get", "'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy':", "for f in found: if f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location':", "Args: bases: A string containing a genetic sequence. Returns: An HTML string. \"\"\"", "ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to = [] for", "cl) output = \"\" for ln, line in enumerate(query): query_from = int(hsp['query_from']) if", "a usable dict. Args: filecontents: The contents of a BLAST XML file. cutoff:", "= [program, '-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50']", "import json import re import hashlib import tempfile import os from lxml import", "= [ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads',", "a string. Args: bases: A string containing a genetic sequence. Returns: An HTML", "'/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found", "lxml import etree import pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\"", "executables. db_loc: Directory containing the BLAST DB. title: The title of the BLAST", "in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'),", "to the BLAST executable. Returns: A tuple containing the stdout and stderr of", "hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'),", "> 0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else:", "sequence is considered relevant. Returns: A dict of the results. \"\"\" results =", "<name> has been created, indicating BLAST has finished, and return results Args: name:", "l=10): \"\"\" Split a string into chunks of a set length. Args: s:", "was created in a BLAST search. Returns: The file or False if it", "bases: A string containing a genetic sequence. Returns: An HTML string. \"\"\" formatted", "it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space':", "= {} for f in found: if f[1].lower() not in databases: databases[f[1].lower()] =", "of the BLAST database to search for. Returns: The location of the BLAST", "if it has not yet been created. \"\"\" try: with open(name) as results:", "b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {},", "0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output", "string. Args: bases: A string containing a genetic sequence. Returns: An HTML string.", "BLAST executables. db: The database to get sequence from. seq_id: The sequence ID", "get_blast_databases(exe_loc, db_loc) flat = [] for k,l in database_list.iteritems(): flat.extend(l) for d in", "name of the database (it may differ from title) Args: exe_loc: Location (directory)", "it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message, stor that for", "results. \"\"\" results = {'results':[], 'messages':[]} messages = [] b = etree.fromstring(filecontents) #", "try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found =", "'-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options,", "if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if", "u'both'}) \"\"\" query = [program, '-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore,", "import base64 import json import re import hashlib import tempfile import os from", "to pass to the BLAST executable. Returns: A tuple containing the stdout and", "of the results. \"\"\" results = {'results':[], 'messages':[]} messages = [] b =", "[{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p", "}, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa': b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'),", "f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases", "\"\"\" Create an list of options filtering out excluded options Args: option_string: A", "p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout,", "[s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours the", "= int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq =", "</pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from),", "or False if it has not yet been created. \"\"\" try: with open(name)", "chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from)", "results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'),", "</div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents,", "return results.read() raise IOError except IOError: return False def chunk_string(s, l=10): \"\"\" Split", "int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line)", "float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from'])) query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] =", "for d in flat: if title == d['title']: return d['location'] return False def", "a BLAST XML results file and process into a usable dict. Args: filecontents:", "flat: if title == d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id):", "d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from the", "class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to )", "it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length': b.xpath('string(Iteration_stat/Statistics/Statistics_hsp-len/text())'), 'eff_space': b.xpath('string(Iteration_stat/Statistics/Statistics_eff-space/text())'), 'kappa':", "the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/',", "db, seq_id): \"\"\" Extract a sequence from the given BLAST database and return", "found)) if len(entry) > 1] databases = {} for f in found: if", "def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results file and process into", "if the file <name> has been created, indicating BLAST has finished, and return", "else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), },", "exclude: Options to exclude from the generated list. Returns: A list of options", "u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand':", "contents of a BLAST XML file. cutoff: The cutoff for which a sequence", "subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc,", "[ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy',", "messages = [] b = etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/')", "cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for", "search for. Returns: The location of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc,", "later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details':", "'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq':", "\"\" for ln, line in enumerate(query): query_from = int(hsp['query_from']) if ln == 0", "'-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "differ from title) Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory", ">>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\"", "import re import hashlib import tempfile import os from lxml import etree import", "options: if o[1] not in exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore,", "databases using in given path and return a list Args: exe_loc: Location (directory)", "The location of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat =", "extras def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST search", "A string containing a genetic sequence. Returns: An HTML string. \"\"\" formatted =", "t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message, stor", "'' found = [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if", "Returns: The sequence if found else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/',", "database and return it Args: exe_loc: Directory containing BLAST executables. db: The database", "the given query Args: database: The database to search (full path). program: The", "f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title get", "The program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to store", "return (stdout, stderr) def poll(name): \"\"\" Check if the file <name> has been", "string to chunk. l: The length of the chunks. Returns: A list containing", "{u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq,", "Any extra options to pass to the BLAST executable. Returns: A tuple containing", "entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1] databases = {}", "= chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\" for ln, line", "<div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre", "\"\"\" query = [program, '-db', database, '-outfmt', '5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid),", "results file and process into a usable dict. Args: filecontents: The contents of", "def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options filtering out excluded options", "string containing a genetic sequence. Returns: An HTML string. \"\"\" formatted = ''", "The contents of a BLAST XML file. cutoff: The cutoff for which a", "get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract a sequence from the given BLAST database and", "else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0 else", "= t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message,", "it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length': b.xpath('string(Iteration_stat/Statistics/Statistics_db-len/text())'), 'hsp_length':", "may differ from title) Args: exe_loc: Location (directory) of the BLAST executables. db_loc:", "database: The database to search (full path). program: The program to use (e.g.", "%t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found", "it Args: exe_loc: Directory containing BLAST executables. db: The database to get sequence", "blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db',", "Perform a BLAST search on the given database using the given query Args:", "'/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn',", "BLAST databases using in given path and return a list Args: exe_loc: Location", "subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div class=\"row\"> <pre", "in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc,", "for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it", "'-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE,", "title == d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\" Extract", "The string to chunk. l: The length of the chunks. Returns: A list", "for i in range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours the bases", "dict containing the sequence information. Returns: An HTML string of the formatted sequence.", "except: found = '' found = [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'',", "those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for", "'-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy',", "BLAST has finished, and return results Args: name: The filename of the file", "file_uuid: A unique identifier for the filename. sequence: The sequence to BLAST. options:", "filtering out excluded options Args: option_string: A string containing extra blast options. exclude:", "int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl)", ">>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand':", "stdout, stderr = p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check if the", "title get the actual name of the database (it may differ from title)", "Take a BLAST XML results file and process into a usable dict. Args:", "create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60)", "# Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue':", "\"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found =", "'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from':", "exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform", "in found: if f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title':", "BLAST database to search for. Returns: The location of the BLAST database. \"\"\"", "= [] b = etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details']", "'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent']", "d in flat: if title == d['title']: return d['location'] return False def get_sequence_from_database(exe_loc,", "f in found: if f[1].lower() not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0],", "= parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr", "os.path.getsize(name) > 0: return results.read() raise IOError except IOError: return False def chunk_string(s,", "options Args: option_string: A string containing extra blast options. exclude: Options to exclude", "finished, and return results Args: name: The filename of the file that was", "'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f", "re.sub(r'\\'', '', found)) if len(entry) > 1] databases = {} for f in", "from title) Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing", "cl = 60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject =", "<pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1", "list of options except those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string)", "{ 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num': b.xpath('string(Iteration_stat/Statistics/Statistics_db-num/text())'), 'db_length':", "hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'),", "''' <div class=\"row\"> <pre class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre>", "</pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div>", "the XML output. file_uuid: A unique identifier for the filename. sequence: The sequence", "genetic sequence. Returns: An HTML string. \"\"\" formatted = '' for b in", "b.xpath('string(Iteration_stat/Statistics/Statistics_kappa/text())'), 'lambda': b.xpath('string(Iteration_stat/Statistics/Statistics_lambda/text())'), 'entropy': b.xpath('string(Iteration_stat/Statistics/Statistics_entropy/text())'), }, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'):", "the file that was created in a BLAST search. Returns: The file or", "database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = [] for k,l in database_list.iteritems():", "tuple containing the stdout and stderr of the program. # Test: >>> seq", "chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output = \"\"", "of a BLAST XML file. cutoff: The cutoff for which a sequence is", "it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length':", "it for display. Args: hsp: A dict containing the sequence information. Returns: An", "'-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude)", "'/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db', database, '-outfmt',", "hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] =", "{match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from),", "o in options: if o[1] not in exclude: extras.extend(o[1:]) return extras def run_blast(database,", "Location (directory) of the BLAST executables. db_loc: Directory containing the BLAST DB. Returns:", "(stdout, stderr) def poll(name): \"\"\" Check if the file <name> has been created,", "the bases in a string. Args: bases: A string containing a genetic sequence.", "= '' found = [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found))", "given database using the given query Args: database: The database to search (full", "{}, } for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text", "seq_id: The sequence ID of the sequence to get. Returns: The sequence if", "Create an list of options filtering out excluded options Args: option_string: A string", "o[1] not in exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid, sequence,", "lists of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa',", "sequence to get. Returns: The sequence if found else an empty string #", "list of options filtering out excluded options Args: option_string: A string containing extra", "0: return results.read() raise IOError except IOError: return False def chunk_string(s, l=10): \"\"\"", "a BLAST search on the given database using the given query Args: database:", "Args: database: The database to search (full path). program: The program to use", "= int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from =", "in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o", "= max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to'] = max(query_to) r['hits'].append(h)", "# The file may contain a message, stor that for later use if", "'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity':", "[] } for ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'),", "out excluded options Args: option_string: A string containing extra blast options. exclude: Options", "blast options. exclude: Options to exclude from the generated list. Returns: A list", "'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame':", "= { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to':", "databases = {} for f in found: if f[1].lower() not in databases: databases[f[1].lower()]", "db_loc: Directory containing the BLAST DB. title: The title of the BLAST database", "query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return", "it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title':", "# Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version':", "stderr = p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check if the file", "'5', '-query', '-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query',", "for BLAST databases using in given path and return a list Args: exe_loc:", "b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take", "DB. Returns: A dict containing lists of databases available. # Test it! >>>", "process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results file and process into a", "= create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'],", "in enumerate(query): query_from = int(hsp['query_from']) if ln == 0 else int(hsp['query_from'])+(ln*cl) query_to =", "} hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) >", "ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from':", "except: found = '' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list", "file_uuid, sequence, options): \"\"\" Perform a BLAST search on the given database using", "'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name =", "BLAST executables. db_loc: Directory containing the BLAST DB. title: The title of the", ">>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'})", "= p.communicate(sequence) return (stdout, stderr) def poll(name): \"\"\" Check if the file <name>", "\">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query =", "qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST", "= int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter: query_from.append(int(hsp['query_from']))", "subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq = format_bases(subject[ln]) output += ''' <div", "output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results file and process", "= [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\"", "raise IOError except IOError: return False def chunk_string(s, l=10): \"\"\" Split a string", "query_from = [] query_to = [] for hs in ht.findall('.//Hsp'): hsp = {", "'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title", "def poll(name): \"\"\" Check if the file <name> has been created, indicating BLAST", "HTML string. \"\"\" formatted = '' for b in bases: formatted += '<span", "'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to = [] for hs", "hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'),", "found = '' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of", "'-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE,", "is considered relevant. Returns: A dict of the results. \"\"\" results = {'results':[],", "'/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"])", "of the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn',", "> 0: return results.read() raise IOError except IOError: return False def chunk_string(s, l=10):", "class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum}", "import etree import pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look", "location of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = []", "create_formatted_sequences(hsp): \"\"\" Take a sequence and format it for display. Args: hsp: A", "executables. db_loc: Directory containing the BLAST DB. Returns: A dict containing lists of", "= chunk_string(hsp['midline'], 60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if", "'-', '-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out', '-subject',", "for ln, line in enumerate(query): query_from = int(hsp['query_from']) if ln == 0 else", "60) hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) >", "ln == 0 else int(hsp['query_from'])+(ln*cl) query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln", "ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to =", "'/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found", "for display. Args: hsp: A dict containing the sequence information. Returns: An HTML", "from the generated list. Returns: A list of options except those in exclude", "sequence. \"\"\" cl = 60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl)", "'' for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp):", "use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': {", "databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a give title get the actual", "= '' for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def", "Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt',", "subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found = '' found =", "{'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]} \"\"\" found =", "actual name of the database (it may differ from title) Args: exe_loc: Location", "seq, {u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db', database, '-outfmt', '5',", "database to search (full path). program: The program to use (e.g. BLASTN, TBLASTN,", "if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to = subject_from+(cl-1) qseq = format_bases(line) sseq", "\"\"\" Take a sequence and format it for display. Args: hsp: A dict", "from lxml import etree import pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc):", "from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using", "to get. Returns: The sequence if found else an empty string # Test:", "that for later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r =", "range(0,len(s),l)] def format_bases(bases): \"\"\" Generate HTML that colours the bases in a string.", "for later use if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = {", "= [] query_to = [] for hs in ht.findall('.//Hsp'): hsp = { 'num':", "'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length':", "if os.path.getsize(name) > 0: return results.read() raise IOError except IOError: return False def", "exclude) query.extend(extra) p = subprocess.Popen(query, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence)", "options): \"\"\" Perform a BLAST search on the given database using the given", "to store the XML output. file_uuid: A unique identifier for the filename. sequence:", "identifier for the filename. sequence: The sequence to BLAST. options: Any extra options", "'-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra", "length. Args: s: The string to chunk. l: The length of the chunks.", "sequence from. seq_id: The sequence ID of the sequence to get. Returns: The", "return extras def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST", "'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], }", "'-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ]", "\"'%f %p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"])", "databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For a", "run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST search on the", "= { 'num': ht.xpath('string(Hit_num/text())'), 'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps':", ">>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}], 'nucleotide': [{'location': '/Users/work/Projects/pyBlast/db/yeast.nt', 'title': 'yeast.nt'}]}", "not in databases: databases[f[1].lower()] = [] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def", "1] databases = {} for f in found: if f[1].lower() not in databases:", "'-out', \"{0}{1}.xml\".format(filestore, file_uuid), '-max_target_seqs', '50'] exclude = [ '-db', '-query', '-out', '-subject', '-html',", "percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using in given path", "of the file that was created in a BLAST search. Returns: The file", "b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'): name", "the BLAST executable. Returns: A tuple containing the stdout and stderr of the", "hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'),", "= get_blast_databases(exe_loc, db_loc) flat = [] for k,l in database_list.iteritems(): flat.extend(l) for d", "1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain", "is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def':", "return results Args: name: The filename of the file that was created in", "string into chunks of a set length. Args: s: The string to chunk.", "hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'),", "'hsps': [], } query_from = [] query_to = [] for hs in ht.findall('.//Hsp'):", "> sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to']", "seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq}", "'-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote', '-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index',", "Returns: A dict containing lists of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/',", "generated list. Returns: A list of options except those in exclude \"\"\" options", "r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics':", "return False def chunk_string(s, l=10): \"\"\" Split a string into chunks of a", "'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t in b.findall('BlastOutput_param/Parameters/*'):", "= \"\" for ln, line in enumerate(query): query_from = int(hsp['query_from']) if ln ==", "{sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to,", "BLAST search on the given database using the given query Args: database: The", "t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for it in b.findall('BlastOutput_iterations/Iteration'): # The file may", "in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a", "hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent']", "The length of the chunks. Returns: A list containing the string chunks. \"\"\"", "'-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra) p", "of the BLAST executables. db_loc: Directory containing the BLAST DB. title: The title", "[] for hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score':", "options: Any extra options to pass to the BLAST executable. Returns: A tuple", "from. seq_id: The sequence ID of the sequence to get. Returns: The sequence", "stderr of the program. # Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt',", "'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'), 'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame':", "} for t in b.findall('BlastOutput_param/Parameters/*'): name = t.tag.split('_', 1) results['details']['params'][name[-1]] = t.text for", "The sequence ID of the sequence to get. Returns: The sequence if found", "base64 import json import re import hashlib import tempfile import os from lxml", "flat.extend(l) for d in flat: if title == d['title']: return d['location'] return False", "= query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to =", "given query Args: database: The database to search (full path). program: The program", "relevant. Returns: A dict of the results. \"\"\" results = {'results':[], 'messages':[]} messages", "A dict containing lists of databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/')", "u'-strand': u'both'}) \"\"\" query = [program, '-db', database, '-outfmt', '5', '-query', '-', '-out',", "the generated list. Returns: A list of options except those in exclude \"\"\"", "to search for. Returns: The location of the BLAST database. \"\"\" database_list =", "A list of options except those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?',", "in given path and return a list Args: exe_loc: Location (directory) of the", "def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST search on", "an list of options filtering out excluded options Args: option_string: A string containing", "seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return", "results.read() raise IOError except IOError: return False def chunk_string(s, l=10): \"\"\" Split a", "hsp['subject_chunk'] = chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) > sum(query_to):", "a string into chunks of a set length. Args: s: The string to", "{ 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'), 'def': it.xpath('string(Iteration_query-def/text())'), 'length': it.xpath('string(Iteration_query-len/text())'), }, 'statistics': { 'db_num':", "[entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) > 1]", "cutoff=0.0001): \"\"\" Take a BLAST XML results file and process into a usable", "db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db':", "subprocess.check_output([exe_loc+'blastdbcmd', '-db', db, '-entry', seq_id]) except: found = '' return found def parse_extra_options(option_string,", "get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST databases using in given path and return", "Test: >>> seq = \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0,", "Directory containing BLAST executables. db: The database to get sequence from. seq_id: The", "ssnum=str(subject_from), senum=subject_to ) return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML", "Returns: The file or False if it has not yet been created. \"\"\"", "\"\"\" Split a string into chunks of a set length. Args: s: The", "The database to get sequence from. seq_id: The sequence ID of the sequence", "databases available. # Test it! >>> get_blast_databases('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/') {'protein': [{'location': '/Users/work/Projects/pyBlast/db/yeast.aa', 'title': 'yeast.aa'}],", "if title == d['title']: return d['location'] return False def get_sequence_from_database(exe_loc, db, seq_id): \"\"\"", "for hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'),", "try: with open(name) as results: if os.path.getsize(name) > 0: return results.read() raise IOError", "sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from'] = min(query_from) h['query_to'] =", "hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline': hs.xpath('string(Hsp_midline/text())'), } hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if", "Directory containing the BLAST DB. title: The title of the BLAST database to", "Check if the file <name> has been created, indicating BLAST has finished, and", "open(name) as results: if os.path.getsize(name) > 0: return results.read() raise IOError except IOError:", "{senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq, qsnum=str(query_from), qenum=query_to, ssnum=str(subject_from), senum=subject_to ) return output.rstrip()", "the BLAST executables. db_loc: Directory containing the BLAST DB. Returns: A dict containing", "that was created in a BLAST search. Returns: The file or False if", "exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = [] for o in", "hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue': hs.xpath('string(Hsp_evalue/text())'), 'query_from': hs.xpath('string(Hsp_query-from/text())'), 'query_to': hs.xpath('string(Hsp_query-to/text())'), 'hit_from': hs.xpath('string(Hsp_hit-from/text())'),", "the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc) flat = [] for k,l", "stderr) def poll(name): \"\"\" Check if the file <name> has been created, indicating", "query_to = query_from+(cl-1) subject_from = int(hsp['hit_from']) if ln == 0 else int(hsp['hit_from'])+(ln*cl) subject_to", "Returns: An HTML string of the formatted sequence. \"\"\" cl = 60 query", "import pprint from math_tools import percentile def get_blast_databases(exe_loc, db_loc): \"\"\" Look for BLAST", "from the given BLAST database and return it Args: exe_loc: Directory containing BLAST", "'hit_to': hs.xpath('string(Hsp_hit-to/text())'), 'query_frame': hs.xpath('string(Hsp_query-frame/text())'), 'hit_frame': hs.xpath('string(Hsp_hit-frame/text())'), 'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length':", "colours the bases in a string. Args: bases: A string containing a genetic", "= chunk_string(hsp['hit_seq'], 60) h['hsps'].append(hsp) if len(h['hsps']) > 0: if sum(query_from) > sum(query_to): h['query_from']", "'50'] exclude = [ '-db', '-query', '-out', '-subject', '-html', '-gilist', '-negative_gilist', '-entrez_query', '-remote',", "'-outfmt', '-num_threads', '-import_search_strategy', '-export_search_strategy', '-window_masker_db', '-index_name', '-use_index', ] extra = parse_extra_options(options, exclude) query.extend(extra)", "string. \"\"\" formatted = '' for b in bases: formatted += '<span class=\"base-{}\">{}</span>'.format(b,b)", "class=\"col-xs-1 seq-col-sm\">Query Subject </pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match}", "import os from lxml import etree import pprint from math_tools import percentile def", "and process into a usable dict. Args: filecontents: The contents of a BLAST", "hsp['identity_percent'] = int(hsp['identity'])/float(hsp['align_length'])*100 hsp['gaps_percent'] = int(hsp['gaps'])/float(hsp['align_length'])*100 if float(hsp['evalue']) < cutoff: #float(hsp['bit_score']) > bit_score_filter:", "exclude from the generated list. Returns: A list of options except those in", "'identity': hs.xpath('string(Hsp_identity/text())'), 'positive': hs.xpath('string(Hsp_positive/text())'), 'gaps': hs.xpath('string(Hsp_gaps/text())'), 'align_length': hs.xpath('string(Hsp_align-len/text())'), 'query_seq': hs.xpath('string(Hsp_qseq/text())'), 'hit_seq': hs.xpath('string(Hsp_hseq/text())'), 'midline':", "Split a string into chunks of a set length. Args: s: The string", "The file or False if it has not yet been created. \"\"\" try:", "'' return found def parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options filtering", "it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id': it.xpath('string(Iteration_query-ID/text())'),", "= min(query_to) else: h['query_from'] = min(query_from) h['query_to'] = max(query_to) r['hits'].append(h) results['results'].append(r) return results", "Generate HTML that colours the bases in a string. Args: bases: A string", "extra blast options. exclude: Options to exclude from the generated list. Returns: A", "filestore, file_uuid, sequence, options): \"\"\" Perform a BLAST search on the given database", "on the given database using the given query Args: database: The database to", "output. file_uuid: A unique identifier for the filename. sequence: The sequence to BLAST.", "title) Args: exe_loc: Location (directory) of the BLAST executables. db_loc: Directory containing the", "if it.find('.//Iteration_message') is not None: results['messages'].append(it.find('.//Iteration_message').text) else: r = { 'details': { 'id':", "process into a usable dict. Args: filecontents: The contents of a BLAST XML", "found = '' found = [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '',", "get sequence from. seq_id: The sequence ID of the sequence to get. Returns:", "file may contain a message, stor that for later use if it.find('.//Iteration_message') is", "in database_list.iteritems(): flat.extend(l) for d in flat: if title == d['title']: return d['location']", "formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and format it for display. Args:", "+= '<span class=\"base-{}\">{}</span>'.format(b,b) return formatted def create_formatted_sequences(hsp): \"\"\" Take a sequence and format", "chunks. Returns: A list containing the string chunks. \"\"\" return [s[i:i+l] for i", "<pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq,", "{ 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'),", "10.0, u'-strand': u'both'}) >>> seq = \">test\\\\nTTC\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue':", "ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = []", "directory to store the XML output. file_uuid: A unique identifier for the filename.", "name: The filename of the file that was created in a BLAST search.", "60 query = chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl)", "0: if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from']", "for it in b.findall('BlastOutput_iterations/Iteration'): # The file may contain a message, stor that", "= [entry.split(' ',2) for entry in re.split(r'\\n', re.sub(r'\\'', '', found)) if len(entry) >", "'db': db_loc[-1], 'query_id': b.xpath('string(BlastOutput_query-ID/text())'), 'query_def': b.xpath('string(BlastOutput_query-def/text())'), 'query_length': b.xpath('string(BlastOutput_query-len/text())'), 'params': {}, } for t", "{u'-evalue': 10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db', database, '-outfmt', '5', '-query',", "sequence ID of the sequence to get. Returns: The sequence if found else", "seq-col-lg\">{qseq} {match} {sseq} </pre> <pre class=\"col-xs-1 seq-col-sm\">{qenum} {senum} </pre> </div> '''.format(qseq=qseq, match=match[ln], sseq=sseq,", "= b.xpath('string(BlastOutput_db/text())').split('/') results['details'] = { 'program': b.xpath('string(BlastOutput_program/text())'), 'version': b.xpath('string(BlastOutput_version/text())'), 'reference': b.xpath('string(BlastOutput_reference/text())'), 'db': db_loc[-1],", "re import hashlib import tempfile import os from lxml import etree import pprint", "for. Returns: The location of the BLAST database. \"\"\" database_list = get_blast_databases(exe_loc, db_loc)", "'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from = [] query_to", "db_loc, title): \"\"\" For a give title get the actual name of the", "of the sequence to get. Returns: The sequence if found else an empty", "10.0, u'-strand': u'both'}) \"\"\" query = [program, '-db', database, '-outfmt', '5', '-query', '-',", "containing BLAST executables. db: The database to get sequence from. seq_id: The sequence", "return output.rstrip() def process_blast_result(filecontents, cutoff=0.0001): \"\"\" Take a BLAST XML results file and", "= \">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>>", "parse_extra_options(option_string, exclude=[]): \"\"\" Create an list of options filtering out excluded options Args:", "(it may differ from title) Args: exe_loc: Location (directory) of the BLAST executables.", "hs in ht.findall('.//Hsp'): hsp = { 'num': hs.xpath('string(Hsp_num/text())'), 'bit_score': hs.xpath('string(Hsp_bit-score/text())'), 'score': hs.xpath('string(Hsp_score/text())'), 'evalue':", "of the chunks. Returns: A list containing the string chunks. \"\"\" return [s[i:i+l]", "%p %t'\"]) try: found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except:", "} query_from = [] query_to = [] for hs in ht.findall('.//Hsp'): hsp =", "[] databases[f[1].lower()].append({'location': f[0], 'title': f[2]}) return databases def get_blast_database_from_title(exe_loc, db_loc, title): \"\"\" For", "for which a sequence is considered relevant. Returns: A dict of the results.", "}, 'hits': [] } for ht in it.findall('Iteration_hits/Hit'): h = { 'num': ht.xpath('string(Hit_num/text())'),", "program to use (e.g. BLASTN, TBLASTN, BLASTX). filestore: The directory to store the", "the BLAST database to search for. Returns: The location of the BLAST database.", "except those in exclude \"\"\" options = re.findall(r'((-\\w+) ([\\w\\d\\.]+)?)\\s?', option_string) extras = []", "in exclude: extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\"", "if sum(query_from) > sum(query_to): h['query_from'] = max(query_from) h['query_to'] = min(query_to) else: h['query_from'] =", "if found else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\"", "containing the string chunks. \"\"\" return [s[i:i+l] for i in range(0,len(s),l)] def format_bases(bases):", "search on the given database using the given query Args: database: The database", "bases in a string. Args: bases: A string containing a genetic sequence. Returns:", "to BLAST. options: Any extra options to pass to the BLAST executable. Returns:", "'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try: found", "using the given query Args: database: The database to search (full path). program:", "= chunk_string(hsp['query_seq'], cl) match = chunk_string(hsp['midline'], cl) subject = chunk_string(hsp['hit_seq'], cl) output =", "s: The string to chunk. l: The length of the chunks. Returns: A", "A string containing extra blast options. exclude: Options to exclude from the generated", "BLAST DB. title: The title of the BLAST database to search for. Returns:", "\">test\\\\nTTCATAATTAATTTTTTATATATATATTATATTATAATATTAATTTATATTATAAAAATAATATTTATTATTAAAATATT\\\\nTATTCTCCTTTCGGGGTTCCGGCTCCCGTGGCCGGGCCCCGGAATTATTAATTAATAATAAATTATTATTAATAATTATT\\\\n>test 2\\\\nAATGGTATTAGATTCAGTGAATTTGGTACAAGACGTCGTAGATCTCTGAAGGCTCAAGATCTAATTATGCAAGGAATCATGAAAGCTGTGAACGGTAACCCAGACAGAAACAAATCGCTATTATTAGGCACATCAAATATTTTATTTGCCAAGAAATATGGAGTCAAGCCAATCGGTACTGTGGCTCACGAGTGGGTTATGGGAGTCGCTTCTATTAGTGAAGATTATTTGCATGCCAATAAAAATGCAATGGATTGTTGGATCAATACTTTTGGTGCAAAAAATGCTGGTTTAGCATTAACGGATACTTTTGGAACTGATGACTTTTTAAAATCATTCCGTCCACCATATTCTGATGCTTACGTCGGTGTTAGACAAGATTCTGGAGACCCAGTTGAGTATACCAAAAAGATTTCCCACCATTACCATGACGTGTTGAAATTGCCTAAATTCTCGAAGATTATCTGTTATTCCGATTCTTTGAACGTCGAAAAGGCAATAACTTACTCCCATGCAGCTAAAGAGAATG\" >>> blast('/Users/work/Projects/pyBlast/db/yeast.nt', '/Users/work/Projects/pyBlast/bin/blastn', '/Users/work/Projects/pyBlast/store/', seq, {u'-evalue': 10.0, u'-strand': u'both'}) >>> seq", "extras.extend(o[1:]) return extras def run_blast(database, program, filestore, file_uuid, sequence, options): \"\"\" Perform a", "</pre> <pre class=\"col-xs-1 seq-col-sm\">{qsnum} {ssnum} </pre> <pre class=\"col-xs-7 seq-col-lg\">{qseq} {match} {sseq} </pre> <pre", "Args: name: The filename of the file that was created in a BLAST", "[] b = etree.fromstring(filecontents) # Get BLAST details db_loc = b.xpath('string(BlastOutput_db/text())').split('/') results['details'] =", "stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) stdout, stderr = p.communicate(sequence) return (stdout, stderr) def poll(name):", "and format it for display. Args: hsp: A dict containing the sequence information.", "'title': 'yeast.nt'}]} \"\"\" found = subprocess.check_output([exe_loc+'blastdbcmd', '-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) try:", "format it for display. Args: hsp: A dict containing the sequence information. Returns:", "query_to.append(int(hsp['query_to'])) hsp['formatted'] = create_formatted_sequences(hsp) hsp['query_chunk'] = chunk_string(hsp['query_seq'], 60) hsp['match_chunk'] = chunk_string(hsp['midline'], 60) hsp['subject_chunk']", "pass to the BLAST executable. Returns: A tuple containing the stdout and stderr", "chunk_string(s, l=10): \"\"\" Split a string into chunks of a set length. Args:", "'id': ht.xpath('string(Hit_id/text())'), 'def': ht.xpath('string(Hit_def/text())'), 'accession': ht.xpath('string(Hit_accession/text())'), 'length': ht.xpath('string(Hit_len/text())'), 'hsps': [], } query_from =", "Take a sequence and format it for display. Args: hsp: A dict containing", "else an empty string # Test: >>> get_sequence_from_database('/Users/work/Projects/pyBlast/bin/', '/Users/work/Projects/pyBlast/db/yeast.nt', 'gi|6226515|ref|NC_001224.1|') \"\"\" try: found", "'-list', db_loc, '-list_outfmt', \"'%f %p %t'\"]) except: found = '' found = [entry.split('" ]
[]
[ "to long url mapping. ''' id = db.Column('id', db.Integer, primary_key = True) uuid", "mapping. ''' id = db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer,", "db.String(255), unique = True) def __init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid", "flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model): '''", "Created on 02-Jul-2016 @author: <NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import", "from restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible", "True) def __init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid = uuid self.short_url", "for storing shortened to long url mapping. ''' id = db.Column('id', db.Integer, primary_key", "url): ''' Constructor ''' self.uuid = uuid self.short_url = short_url self.url = url", "class UrlMap(db.Model): ''' A model responsible for storing shortened to long url mapping.", "db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer, unique = True) short_url =", "= True) def __init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid = uuid", "True) uuid = db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url', db.String(255), unique", "= db.Column('short_url', db.String(255), unique = True) url = db.Column('url', db.String(255), unique = True)", "model responsible for storing shortened to long url mapping. ''' id = db.Column('id',", "@version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app", "from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model):", "= True) short_url = db.Column('short_url', db.String(255), unique = True) url = db.Column('url', db.String(255),", "1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app)", "unique = True) def __init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid =", "@author: <NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes", "= db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer, unique = True)", "on 02-Jul-2016 @author: <NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy", "db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer, unique = True) short_url", "UrlMap(db.Model): ''' A model responsible for storing shortened to long url mapping. '''", "storing shortened to long url mapping. ''' id = db.Column('id', db.Integer, primary_key =", "uuid, short_url, url): ''' Constructor ''' self.uuid = uuid self.short_url = short_url self.url", "short_url, url): ''' Constructor ''' self.uuid = uuid self.short_url = short_url self.url =", "short_url = db.Column('short_url', db.String(255), unique = True) url = db.Column('url', db.String(255), unique =", "''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app) class", "db.Integer, unique = True) short_url = db.Column('short_url', db.String(255), unique = True) url =", "restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for", "def __init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid = uuid self.short_url =", "db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url', db.String(255), unique = True) url", "= True) url = db.Column('url', db.String(255), unique = True) def __init__(self, uuid, short_url,", "''' Created on 02-Jul-2016 @author: <NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy", "url mapping. ''' id = db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid',", "primary_key = True) uuid = db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url',", "''' A model responsible for storing shortened to long url mapping. ''' id", "<NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import", "True) url = db.Column('url', db.String(255), unique = True) def __init__(self, uuid, short_url, url):", "02-Jul-2016 @author: <NAME> @version: 1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from", "db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for storing shortened to", "SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for storing shortened to long url", "A model responsible for storing shortened to long url mapping. ''' id =", "app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for storing shortened", "unique = True) url = db.Column('url', db.String(255), unique = True) def __init__(self, uuid,", "uuid = db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url', db.String(255), unique =", "url = db.Column('url', db.String(255), unique = True) def __init__(self, uuid, short_url, url): '''", "db.Column('url', db.String(255), unique = True) def __init__(self, uuid, short_url, url): ''' Constructor '''", "True) short_url = db.Column('short_url', db.String(255), unique = True) url = db.Column('url', db.String(255), unique", "= db.Column('url', db.String(255), unique = True) def __init__(self, uuid, short_url, url): ''' Constructor", "= SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for storing shortened to long", "shortened to long url mapping. ''' id = db.Column('id', db.Integer, primary_key = True)", "responsible for storing shortened to long url mapping. ''' id = db.Column('id', db.Integer,", "@since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db =", "long url mapping. ''' id = db.Column('id', db.Integer, primary_key = True) uuid =", "= True) uuid = db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url', db.String(255),", "id = db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer, unique =", "db.String(255), unique = True) url = db.Column('url', db.String(255), unique = True) def __init__(self,", "db.Column('short_url', db.String(255), unique = True) url = db.Column('url', db.String(255), unique = True) def", "= db.Column('uuid', db.Integer, unique = True) short_url = db.Column('short_url', db.String(255), unique = True)", "import app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model responsible for storing", "''' id = db.Column('id', db.Integer, primary_key = True) uuid = db.Column('uuid', db.Integer, unique", "__init__(self, uuid, short_url, url): ''' Constructor ''' self.uuid = uuid self.short_url = short_url", "SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A model", "import SQLAlchemy from restful.tiny_routes import app db = SQLAlchemy(app) class UrlMap(db.Model): ''' A", "unique = True) short_url = db.Column('short_url', db.String(255), unique = True) url = db.Column('url',", "1.0 @since: 1.0 ''' from flask_sqlalchemy import SQLAlchemy from restful.tiny_routes import app db" ]
[ "dct, idct def dct2(a): return dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho'", "np from scipy.fftpack import dct, idct def dct2(a): return dct( dct( a, axis=0,", "= 200 table = [] for i in range( 256 ): if i", ", norm='ortho') def binarizeImg(img): threshold = 200 table = [] for i in", "axis=1 , norm='ortho') def binarizeImg(img): threshold = 200 table = [] for i", "a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold = 200 table", "dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return idct( idct(", "norm='ortho' ) def idct2(a): return idct( idct( a, axis=0 , norm='ortho'), axis=1 ,", "norm='ortho') def binarizeImg(img): threshold = 200 table = [] for i in range(", "def binarizeImg(img): threshold = 200 table = [] for i in range( 256", "256 ): if i < threshold: table.append(0) else: table.append(1) tmp_img = img.point(table) return", "a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return idct( idct( a,", "axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return idct( idct( a, axis=0", "200 table = [] for i in range( 256 ): if i <", "<gh_stars>1-10 import numpy as np from scipy.fftpack import dct, idct def dct2(a): return", "norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return idct( idct( a, axis=0 ,", "from scipy.fftpack import dct, idct def dct2(a): return dct( dct( a, axis=0, norm='ortho'", "range( 256 ): if i < threshold: table.append(0) else: table.append(1) tmp_img = img.point(table)", "def dct2(a): return dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def", "): if i < threshold: table.append(0) else: table.append(1) tmp_img = img.point(table) return np.array(tmp_img)", "), axis=1, norm='ortho' ) def idct2(a): return idct( idct( a, axis=0 , norm='ortho'),", "idct def dct2(a): return dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' )", "idct( idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold =", "dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return idct(", "norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold = 200 table = [] for", "axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold = 200 table =", "numpy as np from scipy.fftpack import dct, idct def dct2(a): return dct( dct(", "idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold = 200", "in range( 256 ): if i < threshold: table.append(0) else: table.append(1) tmp_img =", "binarizeImg(img): threshold = 200 table = [] for i in range( 256 ):", "scipy.fftpack import dct, idct def dct2(a): return dct( dct( a, axis=0, norm='ortho' ),", "dct2(a): return dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a):", "for i in range( 256 ): if i < threshold: table.append(0) else: table.append(1)", "return idct( idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold", "import numpy as np from scipy.fftpack import dct, idct def dct2(a): return dct(", "i in range( 256 ): if i < threshold: table.append(0) else: table.append(1) tmp_img", "import dct, idct def dct2(a): return dct( dct( a, axis=0, norm='ortho' ), axis=1,", "threshold = 200 table = [] for i in range( 256 ): if", "= [] for i in range( 256 ): if i < threshold: table.append(0)", "as np from scipy.fftpack import dct, idct def dct2(a): return dct( dct( a,", "idct2(a): return idct( idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img):", "axis=1, norm='ortho' ) def idct2(a): return idct( idct( a, axis=0 , norm='ortho'), axis=1", "def idct2(a): return idct( idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho') def", "table = [] for i in range( 256 ): if i < threshold:", "[] for i in range( 256 ): if i < threshold: table.append(0) else:", ", norm='ortho'), axis=1 , norm='ortho') def binarizeImg(img): threshold = 200 table = []", ") def idct2(a): return idct( idct( a, axis=0 , norm='ortho'), axis=1 , norm='ortho')", "return dct( dct( a, axis=0, norm='ortho' ), axis=1, norm='ortho' ) def idct2(a): return" ]
[ "list_of_strings = [input() for _ in range(n)] filtered_list = [] for i in", "[input() for _ in range(n)] filtered_list = [] for i in range(n): if", "= [input() for _ in range(n)] filtered_list = [] for i in range(n):", "in range(n)] filtered_list = [] for i in range(n): if word in list_of_strings[i]:", "range(n)] filtered_list = [] for i in range(n): if word in list_of_strings[i]: filtered_list.append(list_of_strings[i])", "_ in range(n)] filtered_list = [] for i in range(n): if word in", "= [] for i in range(n): if word in list_of_strings[i]: filtered_list.append(list_of_strings[i]) print(list_of_strings) print(filtered_list)", "n = int(input()) word = input() list_of_strings = [input() for _ in range(n)]", "for _ in range(n)] filtered_list = [] for i in range(n): if word", "word = input() list_of_strings = [input() for _ in range(n)] filtered_list = []", "int(input()) word = input() list_of_strings = [input() for _ in range(n)] filtered_list =", "filtered_list = [] for i in range(n): if word in list_of_strings[i]: filtered_list.append(list_of_strings[i]) print(list_of_strings)", "= int(input()) word = input() list_of_strings = [input() for _ in range(n)] filtered_list", "= input() list_of_strings = [input() for _ in range(n)] filtered_list = [] for", "input() list_of_strings = [input() for _ in range(n)] filtered_list = [] for i" ]
[ "'' # initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load", "= MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card with video pc", "ml.first.media_key # create Poll Card with video pc = PollCard(account) pc.duration_in_minutes = 10080", "'' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize the client client =", "= 10080 # one week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name =", "CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID", "video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card with", "= 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name + ' poll card from", "media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card with video pc = PollCard(account)", "# one week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name +", "'' ACCOUNT_ID = '' # initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,", "ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card with video", "one week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name + '", "load the advertiser account instance account = client.accounts(ACCOUNT_ID) # most recent Media Library", "= client.accounts(ACCOUNT_ID) # most recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key", "week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name + ' poll", "' poll card from SDK' pc.media_key = media_key pc.save() # create Tweet Tweet.create(account,", "most recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key #", "ACCESS_TOKEN_SECRET) # load the advertiser account instance account = client.accounts(ACCOUNT_ID) # most recent", "ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance account = client.accounts(ACCOUNT_ID) # most", "from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = ''", "CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' #", "= '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize the client client", "the advertiser account instance account = client.accounts(ACCOUNT_ID) # most recent Media Library video", "= ml.first.media_key # create Poll Card with video pc = PollCard(account) pc.duration_in_minutes =", "Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card", "create Poll Card with video pc = PollCard(account) pc.duration_in_minutes = 10080 # one", "# load the advertiser account instance account = client.accounts(ACCOUNT_ID) # most recent Media", "pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name + ' poll card", "client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance account", "CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance account = client.accounts(ACCOUNT_ID) #", "ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize the client", "ml.first.name + ' poll card from SDK' pc.media_key = media_key pc.save() # create", "'' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize the", "# most recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key", "the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account", "= 'Southern' pc.name = ml.first.name + ' poll card from SDK' pc.media_key =", "MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = ''", "Poll Card with video pc = PollCard(account) pc.duration_in_minutes = 10080 # one week", "twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY", "account instance account = client.accounts(ACCOUNT_ID) # most recent Media Library video ml =", "= '' ACCOUNT_ID = '' # initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET,", "card from SDK' pc.media_key = media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere", "instance account = client.accounts(ACCOUNT_ID) # most recent Media Library video ml = MediaLibrary(account).all(account,", "media_key = ml.first.media_key # create Poll Card with video pc = PollCard(account) pc.duration_in_minutes", "ACCOUNT_ID = '' # initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)", "PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice = 'Northern' pc.second_choice = 'Southern'", "import Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY =", "import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET =", "Card with video pc = PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice", "poll card from SDK' pc.media_key = media_key pc.save() # create Tweet Tweet.create(account, text='Which", "with video pc = PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice =", "pc.duration_in_minutes = 10080 # one week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name", "PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN =", "pc.name = ml.first.name + ' poll card from SDK' pc.media_key = media_key pc.save()", "twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET =", "advertiser account instance account = client.accounts(ACCOUNT_ID) # most recent Media Library video ml", "MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll Card with video pc =", "Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = ''", "10080 # one week pc.first_choice = 'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name", "import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = ''", "initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser", "pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do you prefer?', card_uri=pc.card_uri) # https://twitter.com/apimctestface/status/973002610033610753", "ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize the client client = Client(CONSUMER_KEY,", "+ ' poll card from SDK' pc.media_key = media_key pc.save() # create Tweet", "= Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance account =", "SDK' pc.media_key = media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do you", "video pc = PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice = 'Northern'", "pc = PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice = 'Northern' pc.second_choice", "twitter_ads.campaign import Tweet from twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard from", "client.accounts(ACCOUNT_ID) # most recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key =", "MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN", "from SDK' pc.media_key = media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do", "pc.media_key = media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do you prefer?',", "= media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do you prefer?', card_uri=pc.card_uri)", "= ml.first.name + ' poll card from SDK' pc.media_key = media_key pc.save() #", "twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET", "import Tweet from twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum", "= '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID =", "'Southern' pc.name = ml.first.name + ' poll card from SDK' pc.media_key = media_key", "account = client.accounts(ACCOUNT_ID) # most recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO)", "from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE CONSUMER_KEY = '' CONSUMER_SECRET", "= PollCard(account) pc.duration_in_minutes = 10080 # one week pc.first_choice = 'Northern' pc.second_choice =", "= '' # initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) #", "recent Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create", "'Northern' pc.second_choice = 'Southern' pc.name = ml.first.name + ' poll card from SDK'", "pc.second_choice = 'Southern' pc.name = ml.first.name + ' poll card from SDK' pc.media_key", "'' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = ''", "# initialize the client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the", "from twitter_ads.campaign import Tweet from twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard", "client client = Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance", "Client(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) # load the advertiser account instance account = client.accounts(ACCOUNT_ID)", "# create Poll Card with video pc = PollCard(account) pc.duration_in_minutes = 10080 #", "Tweet from twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import", "= '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' ACCOUNT_ID = '' # initialize", "Media Library video ml = MediaLibrary(account).all(account, media_type=MEDIA_TYPE.VIDEO) media_key = ml.first.media_key # create Poll", "media_key pc.save() # create Tweet Tweet.create(account, text='Which hemisphere do you prefer?', card_uri=pc.card_uri) #", "from twitter_ads.client import Client from twitter_ads.creative import MediaLibrary, PollCard from twitter_ads.enum import MEDIA_TYPE" ]
[]
[ "class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations", "2020-01-13 02:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base',", "Django 2.2.7 on 2020-01-13 02:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField(", "[ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo',", "('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo', name='title',", "Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user',", "operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo', name='title', field=models.CharField(blank=True, max_length=255), ),", "Generated by Django 2.2.7 on 2020-01-13 02:32 from django.db import migrations, models class", "2.2.7 on 2020-01-13 02:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "02:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'),", "# Generated by Django 2.2.7 on 2020-01-13 02:32 from django.db import migrations, models", "on 2020-01-13 02:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations =", "migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations = [", "] operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo', name='title', field=models.CharField(blank=True, max_length=255),", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0003_auto_20200113_0225'), ]", "by Django 2.2.7 on 2020-01-13 02:32 from django.db import migrations, models class Migration(migrations.Migration):", "dependencies = [ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user', ),", "= [ ('base', '0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField(", "= [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo', name='title', field=models.CharField(blank=True, max_length=255), ), ]", "'0003_auto_20200113_0225'), ] operations = [ migrations.RemoveField( model_name='photo', name='user', ), migrations.AddField( model_name='photo', name='title', field=models.CharField(blank=True," ]
[ "Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for the last message sent", "version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox", "def once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app import Application", "in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\"", "Firefox with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context", "@click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr", "detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr", "as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app", "import to escape name clashing: from kibitzr.app import Application app = Application() app.telegram_chat()", "logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is called with click group for", "kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for the last", "Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean()", "\"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def", "ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import __version__", "click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return [ point.load() for", "@cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli =", "\"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return", "once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app import Application app", "{ \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\"", "default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for", "CLI extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\",", "\"\"\"Return chat id for the last message sent to Telegram Bot\"\"\" # rename", "kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version():", "clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print", "\"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1)", "to Telegram Bot\"\"\" # rename import to escape name clashing: from kibitzr.app import", "Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx,", "= Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory", "for extension in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list of Kibitzr", "= Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run", "name clashing: from kibitzr.app import Application app = Application() app.telegram_chat() @cli.command() def clean():", "PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli", "ultimate agility while preserving cli context. \"\"\" for extension in load_extensions(): extension(click_group) return", "Application app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage", "\"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli) if __name__", "Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once and", "app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\"", "def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash():", "extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\",", "kibitzr.app import Application app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\"", "and exit\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command()", "change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\"", "from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash", "in the foreground mode\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'],", "PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content()", "point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def", "\"\"\" Each extension is called with click group for ultimate agility while preserving", "click group for ultimate agility while preserving cli context. \"\"\" for extension in", "level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj", "kibitzr in the foreground mode\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=False,", "import logging import click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO,", "logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension", "def telegram_chat(): \"\"\"Return chat id for the last message sent to Telegram Bot\"\"\"", "stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli) if __name__ ==", "from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with", "entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, }", "app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command()", "help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\"", "import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks", "Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr", "\"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app import Application app = Application()", "] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run", "= { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group):", "message sent to Telegram Bot\"\"\" # rename import to escape name clashing: from", "run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app import Application app", "load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return [ point.load() for point in", "sent to Telegram Bot\"\"\" # rename import to escape name clashing: from kibitzr.app", "import Application app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from", "@cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\"", "Each extension is called with click group for ultimate agility while preserving cli", "\"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app import Application app = Application()", "def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return [ point.load() for point", "@click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app import", "nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app", "import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def", "app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import", "app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name):", "import click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING,", "def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level':", "firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name',", "\"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is", "last message sent to Telegram Bot\"\"\" # rename import to escape name clashing:", "@cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox()", "contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli) if __name__ == \"__main__\":", "of Kibitzr CLI extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group()", "import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash", "extension in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI", "is called with click group for ultimate agility while preserving cli context. \"\"\"", "LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version)", "extension(click_group) return click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return [", "return click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return [ point.load()", "Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app", "point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\")", "list of Kibitzr CLI extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ]", "\"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each", "rename import to escape name clashing: from kibitzr.app import Application app = Application()", "Telegram Bot\"\"\" # rename import to escape name clashing: from kibitzr.app import Application", "LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def", "in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx,", "kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create", "for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from", "logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is called with click", "checks once and exit\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'],", "kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr", "kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import", "extension is called with click group for ultimate agility while preserving cli context.", "logging import click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\":", "def stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli)", "names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap()", "@cli.command() def clean(): \"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def", "logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is called", "foreground mode\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command()", "profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name):", "def merge_extensions(click_group): \"\"\" Each extension is called with click group for ultimate agility", "from kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init():", "click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\":", "@cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\"", "kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import", "[ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging", "@click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app import", "\"\"\" for extension in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list of", "name): \"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app import Application app =", "mode\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def", "kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent", "import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\": logging.INFO, \"warning\": logging.WARNING, \"error\": logging.ERROR,", "telegram_chat(): \"\"\"Return chat id for the last message sent to Telegram Bot\"\"\" #", "merge_extensions(click_group): \"\"\" Each extension is called with click group for ultimate agility while", "id for the last message sent to Telegram Bot\"\"\" # rename import to", "agility while preserving cli context. \"\"\" for extension in load_extensions(): extension(click_group) return click_group", "\"warning\": logging.WARNING, \"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is called with", "while preserving cli context. \"\"\" for extension in load_extensions(): extension(click_group) return click_group def", "Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration", "clashing: from kibitzr.app import Application app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean", "kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context", "from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run", "history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash contents\"\"\" from", "stash(): \"\"\"Print stash contents\"\"\" from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli) if", "sys import logging import click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG, \"info\":", "} def merge_extensions(click_group): \"\"\" Each extension is called with click group for ultimate", "log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application", "@click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\" from", "sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import", "\"\"\"Return list of Kibitzr CLI extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\")", "--help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\"", "Bot\"\"\" # rename import to escape name clashing: from kibitzr.app import Application app", "from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1)", "@cli.command() def telegram_chat(): \"\"\"Return chat id for the last message sent to Telegram", "Kibitzr CLI extensions\"\"\" return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\",", "nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app", "def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def", "import sys import logging import click import entrypoints LOG_LEVEL_CODES = { \"debug\": logging.DEBUG,", "def run(ctx, name): \"\"\"Run kibitzr in the foreground mode\"\"\" from kibitzr.app import Application", "escape name clashing: from kibitzr.app import Application app = Application() app.telegram_chat() @cli.command() def", "\"error\": logging.ERROR, } def merge_extensions(click_group): \"\"\" Each extension is called with click group", "{'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version", "@cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command()", "files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for", "__version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from", "return [ point.load() for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()),", "for point in entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context", "persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx,", "log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the", "\"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch", "the foreground mode\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name))", "exit\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name',", "group for ultimate agility while preserving cli context. \"\"\" for extension in load_extensions():", "\"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help", "the last message sent to Telegram Bot\"\"\" # rename import to escape name", "entrypoints.get_group_all(\"kibitzr.cli\") ] @click.group() @click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level):", "once and exit\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name))", "to escape name clashing: from kibitzr.app import Application app = Application() app.telegram_chat() @cli.command()", "import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\"", "chat id for the last message sent to Telegram Bot\"\"\" # rename import", "with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def", "= Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate configuration files\"\"\" from", "init(): \"\"\"Create boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat():", "boilerplate configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat", "from kibitzr.app import Application app = Application() app.telegram_chat() @cli.command() def clean(): \"\"\"Clean change", "configuration files\"\"\" from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id", "for the last message sent to Telegram Bot\"\"\" # rename import to escape", "with click group for ultimate agility while preserving cli context. \"\"\" for extension", "name): \"\"\"Run kibitzr checks once and exit\"\"\" from kibitzr.app import Application app =", "cli context. \"\"\" for extension in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return", "= {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as", "COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print", "@cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command()", "def version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def", "for ultimate agility while preserving cli context. \"\"\" for extension in load_extensions(): extension(click_group)", "kibitzr checks once and exit\"\"\" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True,", "from kibitzr.stash import Stash Stash.print_content() extended_cli = merge_extensions(cli) if __name__ == \"__main__\": extended_cli()", "log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command()", "from kibitzr.app import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for the", "import Application app = Application() sys.exit(app.run(once=False, log_level=ctx.obj['log_level'], names=name)) @cli.command() def init(): \"\"\"Create boilerplate", "load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list of Kibitzr CLI extensions\"\"\" return", "@click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj =", "version(): \"\"\"Print version\"\"\" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox():", "preserving cli context. \"\"\" for extension in load_extensions(): extension(click_group) return click_group def load_extensions():", "# rename import to escape name clashing: from kibitzr.app import Application app =", "Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for the last message sent to", "def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import Application Application().run_firefox() @cli.command()", "\"\"\"Clean change history\"\"\" from kibitzr.storage import PageHistory PageHistory.clean() @cli.command() def stash(): \"\"\"Print stash", "print(kibitzr_version) @cli.command() def firefox(): \"\"\"Launch Firefox with persistent profile\"\"\" from kibitzr.app import Application", "sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in", "called with click group for ultimate agility while preserving cli context. \"\"\" for", "descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cli.command() def version(): \"\"\"Print version\"\"\" from kibitzr import", "import Application Application.bootstrap() @cli.command() def telegram_chat(): \"\"\"Return chat id for the last message", "context. \"\"\" for extension in load_extensions(): extension(click_group) return click_group def load_extensions(): \"\"\"Return list", "type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed", "@click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once and exit\"\"\" from", "cli(ctx, log_level): \"\"\"Run kibitzr COMMAND --help for detailed descriptions\"\"\" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]}", "Application Application().run_firefox() @cli.command() @click.argument('name', nargs=-1) @click.pass_context def once(ctx, name): \"\"\"Run kibitzr checks once", "names=name)) @cli.command() @click.argument('name', nargs=-1) @click.pass_context def run(ctx, name): \"\"\"Run kibitzr in the foreground", "@click.option(\"-l\", \"--log-level\", default=\"info\", type=click.Choice(LOG_LEVEL_CODES.keys()), help=\"Logging level\") @click.pass_context def cli(ctx, log_level): \"\"\"Run kibitzr COMMAND" ]
[ "'-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [", "self.assertEqual(res, exp) def test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O',", "self.assertEqual(res, 'O') def test_str(self): string = ('X - X - X\\n' 'X X", "X - X # X X X X O # - - -", "= ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X - X -", "-\\n' '- - - - X') res = str(self.board) self.assertEqual(string, res) res =", "in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col in", "def test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res =", "for i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for", "= self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row in", "# X X X X O # - - - - - #", "for i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected", "self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string =", "- - - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res", "0), (0, 3), (0, 1), (3, 3) ] expected = [ '-', 'X',", "- -\\n' 'X X X X -\\n' '- - - - X') res", "str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board)", "test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20) b2", "exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col in enumerate(self.board.cols): exp", "'-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X'", "res = repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res, 25) def", "[ '-', 'X', 'X', 'X' ] results = [ self.board.get(x, y) for x,", "= self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res,", "] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [ (0, 0),", "# - - - - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def", "- X - X\\n' 'X X X X O\\n' '- - - -", "'----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X - X - X #", "self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row in enumerate(self.board.rows):", "self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res", "'-O', 'X' ] for i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp)", "- - - # X X X X - # - - -", "results) def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def", "X X X O # - - - - - # X X", "in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col", "diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected", "= str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def test_len(self): res =", "self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O',", "- # - - - - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5)", "- - - X') res = str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string,", "i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i,", "'-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords", "] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res,", "'X X X X -\\n' '- - - - X') res = str(self.board)", "X -\\n' '- - - - X') res = str(self.board) self.assertEqual(string, res) res", "def test_rows(self): for i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def", "b1 = Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2) b1.set(0, 0, 'x')", "- X') res = str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def", "import Board class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board = ''.join([", "X - X\\n' 'X X X X O\\n' '- - - - -\\n'", "'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def", "self.board = Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ])", "self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X', 'X-',", "coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1)", "self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string = ('X - X - X\\n'", "- - # X X X X - # - - - -", "Board class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board = ''.join([ '----X',", "'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for diag, exp in enumerate(expected): res", "= self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-', 'X-', '-X-',", "- - -\\n' 'X X X X -\\n' '- - - - X')", "self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col)", "X - X - X # X X X X O # -", "= [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for", "in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [", "<reponame>meyer1994/connect5 from unittest import TestCase from ai.board import Board class TestBoard(TestCase): def setUp(self):", "'XXXXO', 'X-X-X' ]) # X - X - X # X X X", "test_rows(self): for i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self):", "= Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2) b1.set(0, 0, 'x') self.assertNotEqual(b1,", "= repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self):", "= list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [ (0, 0), (0, 3),", "= 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row in enumerate(self.board.rows): exp =", "self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col in enumerate(self.board.cols): exp = self.board.col(i)", "for diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self):", "- X - X # X X X X O # - -", "self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row)", "'-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--',", "def test_get(self): coords = [ (0, 0), (0, 3), (0, 1), (3, 3)", "'X X X X O\\n' '- - - - -\\n' 'X X X", "col) def test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res =", "X X X O\\n' '- - - - -\\n' 'X X X X", "-\\n' 'X X X X -\\n' '- - - - X') res =", "res) res = repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res, 25)", "res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [ 'X', 'X-', '-XX',", "'-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i, exp", "'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results =", "self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1,", "(3, 3) ] expected = [ '-', 'X', 'X', 'X' ] results =", "= Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) #", "'-X-O', '-X-', '--', 'X' ] for diag, exp in enumerate(expected): res = self.board.rdiag(diag)", "X X X X O # - - - - - # X", "- - - -\\n' 'X X X X -\\n' '- - - -", "TestCase from ai.board import Board class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5)", "X # X X X X O # - - - - -", "= '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-',", "res) def test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20,", "row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col", "row = '----X' self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row)", "[ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-',", "test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col", "] for diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def", "exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected =", "- - - - # X X X X - # - -", "= self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col in enumerate(self.board.cols): exp =", "X X X X - # - - - - X def test_constructor(self):", "# X - X - X # X X X X O #", "def test_col(self): res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3)", "- - - - - # X X X X - # -", "'- - - - X') res = str(self.board) self.assertEqual(string, res) res = repr(self.board)", "y in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res =", "'-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags)", "'X', 'X' ] results = [ self.board.get(x, y) for x, y in coords", "enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col =", "test_eq(self): b1 = Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2) b1.set(0, 0,", "exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0) col = '-X-XX'", "col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected =", "def test_cols(self): for i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def", "len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20) b2 = Board(20, 20)", "exp) def test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-',", "print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res,", "row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row in enumerate(self.board.rows): exp", "'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-',", "- X # X X X X O # - - - -", "X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board))", "= self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-',", "# X X X X - # - - - - X def", "'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX',", "'-X-XX', '-X-O', '-X-', '--', 'X' ] for diag, exp in enumerate(expected): res =", "test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X',", "5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res", "(0, 0), (0, 3), (0, 1), (3, 3) ] expected = [ '-',", "1), (3, 3) ] expected = [ '-', 'X', 'X', 'X' ] results", "= [ (0, 0), (0, 3), (0, 1), (3, 3) ] expected =", "'X', 'X', 'X' ] results = [ self.board.get(x, y) for x, y in", "self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO'", "enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [ 'X', 'X-',", "'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [ (0,", "Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X", "= [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-',", "[ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for diag,", "res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20) b2 =", "'XX-XX', '-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self):", "3) ] expected = [ '-', 'X', 'X', 'X' ] results = [", "in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [ 'X',", "= len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20) b2 = Board(20,", "X - # - - - - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height,", "'--', 'X' ] for diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res,", "for x, y in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O')", "i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res =", "('X - X - X\\n' 'X X X X O\\n' '- - -", "in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1,", "'-X-', '--', 'X' ] for diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res)", "X X -\\n' '- - - - X') res = str(self.board) self.assertEqual(string, res)", "'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-',", "'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row in enumerate(self.board.rows): exp = self.board.row(i)", "exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [", "self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O')", "expected = [ '-', 'X', 'X', 'X' ] results = [ self.board.get(x, y)", "= self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string = ('X - X -", "1) self.assertEqual(res, 'O') def test_str(self): string = ('X - X - X\\n' 'X", "X O # - - - - - # X X X X", "- - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res =", "5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X -", "expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ]", "= [ '-', 'X', 'X', 'X' ] results = [ self.board.get(x, y) for", "] results = [ self.board.get(x, y) for x, y in coords ] self.assertListEqual(expected,", "- X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0)", "exp) def test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-',", "] expected = [ '-', 'X', 'X', 'X' ] results = [ self.board.get(x,", "setUp(self): self.board = Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X'", "'X' ] for i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def", "X O\\n' '- - - - -\\n' 'X X X X -\\n' '-", "X X X -\\n' '- - - - X') res = str(self.board) self.assertEqual(string,", "X') res = str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def test_len(self):", "self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res,", "= '----X' self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def", "X X - # - - - - X def test_constructor(self): self.assertEqual(self.board.width, 5)", "3), (0, 1), (3, 3) ] expected = [ '-', 'X', 'X', 'X'", "unittest import TestCase from ai.board import Board class TestBoard(TestCase): def setUp(self): self.board =", "x, y in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1, 'O') res", "X\\n' 'X X X X O\\n' '- - - - -\\n' 'X X", "'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for diag, exp in", "self.assertEqual(res, row) def test_rows(self): for i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp,", "expected) def test_get(self): coords = [ (0, 0), (0, 3), (0, 1), (3,", "Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2) b1.set(0, 0, 'x') self.assertNotEqual(b1, b2)", "expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ]", "'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for diag, exp", "res = self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col =", "def test_str(self): string = ('X - X - X\\n' 'X X X X", "class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-',", "- - X') res = str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res)", "row) def test_rows(self): for i, row in enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row)", "col) def test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-',", "res = str(self.board) self.assertEqual(string, res) res = repr(self.board) self.assertEqual(string, res) def test_len(self): res", "(0, 1), (3, 3) ] expected = [ '-', 'X', 'X', 'X' ]", "[ self.board.get(x, y) for x, y in coords ] self.assertListEqual(expected, results) def test_set(self):", "= ('X - X - X\\n' 'X X X X O\\n' '- -", "5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res,", "= self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-'", "'-X-XX' self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self):", "= [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for", "res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res = self.board.row(3) row", "list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [ (0, 0), (0, 3), (0,", "test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X'", "res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i, row", "'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results,", "self.assertListEqual(results, expected) def test_get(self): coords = [ (0, 0), (0, 3), (0, 1),", "[ (0, 0), (0, 3), (0, 1), (3, 3) ] expected = [", "def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row", "def test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--',", "results = [ self.board.get(x, y) for x, y in coords ] self.assertListEqual(expected, results)", "''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X - X - X", "i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected =", "self.board.get(x, y) for x, y in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1,", "def test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self):", "self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X'", "'-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i, exp in enumerate(expected):", "self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 =", "'----X' self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self):", "test_set(self): self.board.set(1, 1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string", "row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for i,", "ai.board import Board class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board =", "col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res = self.board.col(0)", "] for i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self):", "'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string = ('X -", "def setUp(self): self.board = Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO',", "string = ('X - X - X\\n' 'X X X X O\\n' '-", "'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X - X - X # X", "- - - - X def test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self):", "'-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX',", "self.board.ldiag(i) self.assertEqual(res, exp) def test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX',", "'-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ]", "y) for x, y in coords ] self.assertListEqual(expected, results) def test_set(self): self.board.set(1, 1,", "# - - - - - # X X X X - #", "self.board.board = ''.join([ '----X', 'XXXX-', '-----', 'XXXXO', 'X-X-X' ]) # X - X", "TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board = ''.join([ '----X', 'XXXX-', '-----',", "X X O # - - - - - # X X X", "self.assertEqual(res, row) res = self.board.row(3) row = 'XXXXO' self.assertEqual(res, row) def test_rows(self): for", "self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-',", "= [ self.board.get(x, y) for x, y in coords ] self.assertListEqual(expected, results) def", "'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords =", "'XX-', '-O', 'X' ] for i, exp in enumerate(expected): res = self.board.ldiag(i) self.assertEqual(res,", "test_get(self): coords = [ (0, 0), (0, 3), (0, 1), (3, 3) ]", "coords = [ (0, 0), (0, 3), (0, 1), (3, 3) ] expected", "import TestCase from ai.board import Board class TestBoard(TestCase): def setUp(self): self.board = Board(5,", "'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i, exp in enumerate(expected): res =", "'-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X' ] for diag, exp in enumerate(expected):", "from unittest import TestCase from ai.board import Board class TestBoard(TestCase): def setUp(self): self.board", "O # - - - - - # X X X X -", "(0, 3), (0, 1), (3, 3) ] expected = [ '-', 'X', 'X',", "'O') def test_str(self): string = ('X - X - X\\n' 'X X X", "from ai.board import Board class TestBoard(TestCase): def setUp(self): self.board = Board(5, 5) self.board.board", "self.assertEqual(exp, row) def test_cols(self): for i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp,", "col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X', 'X-', '-XX',", "'--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results", "res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-', 'X-',", "'X' ] for diag, exp in enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp)", "'X' ] results = [ self.board.get(x, y) for x, y in coords ]", "- X\\n' 'X X X X O\\n' '- - - - -\\n' 'X", "'- - - - -\\n' 'X X X X -\\n' '- - -", "col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col)", "'-', 'X', 'X', 'X' ] results = [ self.board.get(x, y) for x, y", "enumerate(expected): res = self.board.rdiag(diag) print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-',", "repr(self.board) self.assertEqual(string, res) def test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1", "'X-X-X' ]) # X - X - X # X X X X", "'-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] results = list(self.board.diags) self.assertListEqual(results, expected)", "'-X--', 'XX-', '-O', 'X' ] for i, exp in enumerate(expected): res = self.board.ldiag(i)", "test_cols(self): for i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self):", "= '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def", "res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string = ('X - X", "test_rdiag(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X'", "expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--', 'X', '-',", "test_str(self): string = ('X - X - X\\n' 'X X X X O\\n'", "1, 'O') res = self.board.get(1, 1) self.assertEqual(res, 'O') def test_str(self): string = ('X", "res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [", "25) def test_eq(self): b1 = Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2)", "def test_diags(self): expected = [ 'X', 'X-', '-XX', 'X-X-', '-X-XX', '-X-O', '-X-', '--',", "'-----', 'XXXXO', 'X-X-X' ]) # X - X - X # X X", "- # X X X X - # - - - - X", "test_row(self): res = self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res = self.board.row(3)", "'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i, exp in enumerate(expected): res", "test_constructor(self): self.assertEqual(self.board.width, 5) self.assertEqual(self.board.height, 5) def test_row(self): res = self.board.row(0) print(type(self.board.board)) row =", "self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected", "= self.board.row(0) print(type(self.board.board)) row = '----X' self.assertEqual(res, row) res = self.board.row(3) row =", "O\\n' '- - - - -\\n' 'X X X X -\\n' '- -", "X X X - # - - - - X def test_constructor(self): self.assertEqual(self.board.width,", "print(res) self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX',", "X X O\\n' '- - - - -\\n' 'X X X X -\\n'", "def test_len(self): res = len(self.board) self.assertEqual(res, 25) def test_eq(self): b1 = Board(20, 20)", "'-X-XX', '-X-O', '-X-', '--', 'X', '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O',", "results = list(self.board.diags) self.assertListEqual(results, expected) def test_get(self): coords = [ (0, 0), (0,", "'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i, exp in", "def test_eq(self): b1 = Board(20, 20) b2 = Board(20, 20) self.assertEqual(b1, b2) b1.set(0,", "= self.board.col(3) col = '-X-X-' self.assertEqual(res, col) def test_rdiag(self): expected = [ 'X',", "]) # X - X - X # X X X X O", "enumerate(self.board.rows): exp = self.board.row(i) self.assertEqual(exp, row) def test_cols(self): for i, col in enumerate(self.board.cols):", "def test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O',", "row) def test_cols(self): for i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col)", "self.assertEqual(res, exp) def test_ldiag(self): expected = [ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--',", "for i, col in enumerate(self.board.cols): exp = self.board.col(i) self.assertEqual(exp, col) def test_col(self): res", "self.board.col(0) col = '-X-XX' self.assertEqual(res, col) res = self.board.col(3) col = '-X-X-' self.assertEqual(res,", "[ '-', 'X-', '-X-', 'X-X-', 'XX-XX', '-X--', 'XX-', '-O', 'X' ] for i," ]
[ "firmware 'v1.10-247-g0fb15fc3f on 2019-03-29'\" DESC = 2 INCL = 1 def open(): pass", "on firmware 'v1.10-247-g0fb15fc3f on 2019-03-29'\" DESC = 2 INCL = 1 def open():", "\"Module 'btree' on firmware 'v1.10-247-g0fb15fc3f on 2019-03-29'\" DESC = 2 INCL = 1", "'btree' on firmware 'v1.10-247-g0fb15fc3f on 2019-03-29'\" DESC = 2 INCL = 1 def" ]
[ "attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield attr_value_selector", "from elm_fluent import compiler items = [] for node in nodes: if isinstance(node,", "map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME],", "back to a string here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value,", "attr_value, expr_replacements ) attr_output_parts = [] for part in attr_value_parts: if isinstance(part, str):", "def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to structure this as a", "specific compilation functions \"\"\" import re import bs4 from fluent.syntax import ast from", "attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class attribute differently,", "last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else:", "a list of ast.Expression objects, returns a string with replacement markers and a", "[] expr_replacements = {} for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else:", "split_text = [p for p in splitter.split(text) if p] return [expr_replacements.get(t, t) for", "have to structure this as a list of lists, then do a List.concat", "compiler_env) if val.type == html_output_type: # This is a list type, so simply", "functions \"\"\" import re import bs4 from fluent.syntax import ast from elm_fluent import", "compilation functions \"\"\" import re import bs4 from fluent.syntax import ast from elm_fluent", ") split_text = [p for p in splitter.split(text) if p] return [expr_replacements.get(t, t)", "def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of", "= interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for part in attr_value_parts: if", "yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p", "part in parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ]", "= codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor", "= dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO -", "is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0])", ") def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to structure this as", "parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements,", "if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for", "replacement that doesn't have any special HTML chars in it # that would", "html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects, returns a string", "= local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes:", "do a List.concat # at the end. In many cases the List.concat will", "= {} for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need", ") ] ) ) else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type ==", "generated string # does not appear by chance in the actual message. replacement_name", "tag_name = node.name.lower() static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value,", "get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements)", "return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement markers,", "and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items = [] for item", "attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\"", "[]) if is_static_only(\" \".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector", "and check the parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return", "parse failures gracefully, and check the parser is ensuring # well-formedness dom =", "replacement markers to expression objects, returns a list containing text/expression objects. \"\"\" if", "codegen.String(str(part)) ) ] ) ) else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type", "cause the HTML parser to do anything funny with it. # TODO -", "<reponame>elm-fluent/elm-fluent \"\"\" HTML specific compilation functions \"\"\" import re import bs4 from fluent.syntax", "yield class_selector yield tag_name + class_selector id = node.attrs.get(\"id\", None) if id is", "\"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text = [p for p in splitter.split(text)", "HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val = compiler.compile_expr(part, local_scope,", "class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name + class_selector id", "def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects, returns a string with", "returns a string with replacement markers and a dictionary of replacement info \"\"\"", "a dictionary of replacement info \"\"\" parts = [] expr_replacements = {} for", "0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat):", "in splitter.split(text) if p] return [expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node,", ") item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes):", "the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements", "in classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name + class_selector id =", "# that would cause the HTML parser to do anything funny with it.", "if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else:", "in replacement_strings)) ) split_text = [p for p in splitter.split(text) if p] return", "items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val = compiler.compile_expr(part,", "return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): #", "tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in", "def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse", "+ class_selector id = node.attrs.get(\"id\", None) if id is not None and is_static_only(id):", "[] for node in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for", "a list, which we convert # back to a string here: attr_value =", "defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton,", "= interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part, str): items.append( HtmlList( [", "fluent.syntax import ast from elm_fluent import codegen from elm_fluent.stubs import defaults as dtypes,", "In many cases the List.concat will disappear after # simplify. from elm_fluent import", "= [] for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False):", "compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if", "local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node", "= node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str)", "codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\"", "for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement", "after # simplify. from elm_fluent import compiler items = [] for node in", "compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[", "for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class attribute", "yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield attr_value_selector yield", "import bs4 from fluent.syntax import ast from elm_fluent import codegen from elm_fluent.stubs import", "str) for p in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for", "replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text", "class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements):", "the end. In many cases the List.concat will disappear after # simplify. from", "( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items = [] for item in", "for item in self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item)", "handle parse failures gracefully, and check the parser is ensuring # well-formedness dom", "bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()): if", "node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_) yield", "We have to structure this as a list of lists, then do a", "anything funny with it. # TODO - some mechanism that would guarantee this", "elm_fluent import codegen from elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type =", "self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects, returns a", "\"\"\" if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r)", "tag_name + class_selector id = node.attrs.get(\"id\", None) if id is not None and", "the List.concat will disappear after # simplify. from elm_fluent import compiler items =", "import re import bs4 from fluent.syntax import ast from elm_fluent import codegen from", "attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = []", ") if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name)", "= [] expr_replacements = {} for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value)", "= local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes =", "= local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name =", "dictionary of replacement markers to expression objects, returns a list containing text/expression objects.", "replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully, and check the parser is", "elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope,", "list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val]))", "lists, then do a List.concat # at the end. In many cases the", "message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text,", "expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor", "local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower()", "as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements", ") ) else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: #", "[p for p in splitter.split(text) if p] return [expr_replacements.get(t, t) for t in", "tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield attr_value_selector yield tag_name", "= HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a", "list containing text/expression objects. \"\"\" if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys())", "interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement markers, and a dictionary of", "if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1]", "isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement that doesn't have any special", "id = node.attrs.get(\"id\", None) if id is not None and is_static_only(id): id_selector =", "bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part, str): items.append(", "attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if", "List.concat # at the end. In many cases the List.concat will disappear after", "= codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[", "retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name,", "chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return", "return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval", "\"#{0}\".format(id) yield id_selector yield tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()): if", "that would guarantee this generated string # does not appear by chance in", "will disappear after # simplify. from elm_fluent import compiler items = [] for", "isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part, str):", "last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return self class", "[\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if", "re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text = [p for p in", "attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env,", "for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string(", "as a list of lists, then do a List.concat # at the end.", "codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor =", "list of lists, then do a List.concat # at the end. In many", "yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield", "well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def", "= [] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats", "codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items = [] for", "[] for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append(", "objects. \"\"\" if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile(", "expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a", "this generated string # does not appear by chance in the actual message.", "if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[", "check the parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm(", "self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item =", "else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for attr_name, attr_value", "compiler_env): # We have to structure this as a list of lists, then", "replacement markers and a dictionary of replacement info \"\"\" parts = [] expr_replacements", "{} for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a", "parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in parts) classes =", "= bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements,", "dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)]", "not self: return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference)", "returns a list containing text/expression objects. \"\"\" if not expr_replacements: return [text] replacement_strings", "None) if id is not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector", "not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name + id_selector", "string with replacement markers and a dictionary of replacement info \"\"\" parts =", "local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in", "if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) )", "\"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value):", "sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield", "replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements):", "else: # Need a replacement that doesn't have any special HTML chars in", "attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class attribute differently, returns", "do anything funny with it. # TODO - some mechanism that would guarantee", "parser to do anything funny with it. # TODO - some mechanism that", "def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name)", "compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: # This is a list type,", "to a string here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements", "html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements)", "in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part,", "at the end. In many cases the List.concat will disappear after # simplify.", "TODO - handle parse failures gracefully, and check the parser is ensuring #", "in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in parts:", "items = [] for node in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node),", "which we convert # back to a string here: attr_value = \" \".join(attr_value)", "node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for", "class_selector = \".{0}\".format(class_) yield class_selector yield tag_name + class_selector id = node.attrs.get(\"id\", None)", "list, which we convert # back to a string here: attr_value = \"", "p] return [expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name =", "differently, returns a list, which we convert # back to a string here:", "structure this as a list of lists, then do a List.concat # at", "= dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor =", "with replacement markers, and a dictionary of replacement markers to expression objects, returns", "return all(isinstance(p, str) for p in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\"", "we convert # back to a string here: attr_value = \" \".join(attr_value) attr_value_parts", "if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) )", "import compiler items = [] for node in nodes: if isinstance(node, bs4.element.NavigableString): parts", "codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env )", "HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval is not self:", "html_output_type: # This is a list type, so simply append to our list", "for node in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part", "ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env", "replacement markers, and a dictionary of replacement markers to expression objects, returns a", "some mechanism that would guarantee this generated string # does not appear by", "with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, ) )", "this as a list of lists, then do a List.concat # at the", "r in replacement_strings)) ) split_text = [p for p in splitter.split(text) if p]", "containing text/expression objects. \"\"\" if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter", "id is not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name", "local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node,", "that doesn't have any special HTML chars in it # that would cause", "parts = [] expr_replacements = {} for element in elements: if isinstance(element, ast.TextElement):", "split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts =", "HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\"", "expr_replacements) for part in parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part))", "codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return self", "attribute differently, returns a list, which we convert # back to a string", "of replacement info \"\"\" parts = [] expr_replacements = {} for element in", "# simplify. from elm_fluent import compiler items = [] for node in nodes:", "type, so simply append to our list of lists items.append(val) else: val =", "codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements,", "attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name)", "if id is not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield", "= local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String,", "else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag)", "if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement that doesn't have any", "node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList,", "\"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node =", "for p in splitter.split(text) if p] return [expr_replacements.get(t, t) for t in split_text]", "else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list(", "expr_replacements) return all(isinstance(p, str) for p in parts) classes = node.attrs.get(\"class\", []) if", "in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts", "local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return", "HTML chars in it # that would cause the HTML parser to do", "classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name + class_selector id = node.attrs.get(\"id\",", "literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given", "local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to structure", "in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class attribute differently, returns a", "val.type == html_output_type: # This is a list type, so simply append to", "= node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval =", "HTML parser to do anything funny with it. # TODO - some mechanism", "# TODO - some mechanism that would guarantee this generated string # does", "interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for part in attr_value_parts: if isinstance(part,", "val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name", "does not appear by chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name]", "for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector =", "compiler_env ), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES:", "parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in classes: class_selector", "\"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value)", "\" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for part", "by chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name)", "expr_replacements ) attr_output_parts = [] for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part)))", "not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items", ") items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for", "ast.TextElement): parts.append(element.value) else: # Need a replacement that doesn't have any special HTML", "appear by chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element", "attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else:", "HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list", "in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in classes:", "\"\"\" Given a list of ast.Expression objects, returns a string with replacement markers", "item in self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ):", "id_selector yield tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in", "to structure this as a list of lists, then do a List.concat #", "parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) )", "objects, returns a list containing text/expression objects. \"\"\" if not expr_replacements: return [text]", "a dictionary of replacement markers to expression objects, returns a list containing text/expression", "isinstance(attr_value, list): # Bs4 treats class attribute differently, returns a list, which we", "static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4", "# well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env )", "compiler_env ) if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply(", "new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts,", ") sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS:", "): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True)", "Given a text with replacement markers, and a dictionary of replacement markers to", "here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts =", "compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value", "), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor", "dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm(", "if is_static_only(\" \".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector yield", "from elm_fluent import codegen from elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type", "elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement that doesn't have", "def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval is not self: return", "expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return", "return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and (", "\"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement markers, and", "dictionary of replacement info \"\"\" parts = [] expr_replacements = {} for element", "[ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val = compiler.compile_expr(part, local_scope, compiler_env)", "in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement that doesn't", "isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()):", "\"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes),", "self).simplify(changes) if retval is not self: return retval def is_html_text_call(item): return ( isinstance(item,", "== \"Html.text\" ) ) new_items = [] for item in self.items: if (", "= \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\"", "str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope,", "Need a replacement that doesn't have any special HTML chars in it #", "any special HTML chars in it # that would cause the HTML parser", "list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text = [p", "] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List(", "node.name.lower() static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): #", "gracefully, and check the parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\")", "dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We", "] ) ) else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type:", "id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector", "is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) ==", "[] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class", "sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes)", "a List.concat # at the end. In many cases the List.concat will disappear", "markers, and a dictionary of replacement markers to expression objects, returns a list", "chars in it # that would cause the HTML parser to do anything", "compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to structure this", "of lists, then do a List.concat # at the end. In many cases", "dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle", "super(HtmlList, self).simplify(changes) if retval is not self: return retval def is_html_text_call(item): return (", "is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name + id_selector for attr_name, attr_value", "t) for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name", "static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) )", "isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val", "\"\"\" parts = [] expr_replacements = {} for element in elements: if isinstance(element,", "= re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text = [p for p", "yield tag_name + class_selector id = node.attrs.get(\"id\", None) if id is not None", "len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if not", "# at the end. In many cases the List.concat will disappear after #", "if attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name", "local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute),", "expr_replacements): \"\"\" Given a text with replacement markers, and a dictionary of replacement", "= list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text =", "if p] return [expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name", "attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for part in attr_value_parts:", "dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes,", "of ast.Expression objects, returns a string with replacement markers and a dictionary of", "tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item", "not appear by chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] =", "dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name", "items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node,", "= codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env", "super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects, returns", "is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope,", "import ast from elm_fluent import codegen from elm_fluent.stubs import defaults as dtypes, html,", ") ) new_items = [] for item in self.items: if ( len(new_items) >", "if val.type == html_output_type: # This is a list type, so simply append", "yield id_selector yield tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name", "items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for attr_name,", "sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor", "markers and a dictionary of replacement info \"\"\" parts = [] expr_replacements =", "isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items = []", "a replacement that doesn't have any special HTML chars in it # that", "for p in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_", "= \"#{0}\".format(id) yield id_selector yield tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()):", "to expression objects, returns a list containing text/expression objects. \"\"\" if not expr_replacements:", "parts.append(element.value) else: # Need a replacement that doesn't have any special HTML chars", "+ id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue", "else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items =", "is_static_only(\" \".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name", "def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement markers, and a dictionary", "id_selector = \"#{0}\".format(id) yield id_selector yield tag_name + id_selector for attr_name, attr_value in", "attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name +", "expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to", "+ attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield attr_value_selector yield tag_name +", "= [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat):", "html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) #", "item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval", "in self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item", ") new_items = [] for item in self.items: if ( len(new_items) > 0", "attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name, attr_value) yield attr_value_selector yield tag_name + attr_value_selector", "simplify. from elm_fluent import compiler items = [] for node in nodes: if", "= node.attrs.get(\"id\", None) if id is not None and is_static_only(id): id_selector = \"#{0}\".format(id)", ") else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: # This", "class attribute differently, returns a list, which we convert # back to a", "codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node", "isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return", "expr_replacements = {} for element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: #", "= [] for node in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements)", "objects, returns a string with replacement markers and a dictionary of replacement info", "new_items = [] for item in self.items: if ( len(new_items) > 0 and", "return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type)", "import codegen from elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html)", "nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in parts: if", "local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat(", "val = compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: # This is a", "TODO - some mechanism that would guarantee this generated string # does not", "bs4 from fluent.syntax import ast from elm_fluent import codegen from elm_fluent.stubs import defaults", "list): # Bs4 treats class attribute differently, returns a list, which we convert", "HTML specific compilation functions \"\"\" import re import bs4 from fluent.syntax import ast", "class_selector yield tag_name + class_selector id = node.attrs.get(\"id\", None) if id is not", "attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope,", "for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def", "attr_output_parts = [] for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with", "local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val = compiler.compile_expr(part, local_scope, compiler_env) if", "# Bs4 treats class attribute differently, returns a list, which we convert #", "\".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name +", "part, local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name", "retval = super(HtmlList, self).simplify(changes) if retval is not self: return retval def is_html_text_call(item):", "local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes =", "get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node )", "p in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in", "simply append to our list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val,", "[expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield", "continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector", "local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully,", "new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items", "would cause the HTML parser to do anything funny with it. # TODO", "that would cause the HTML parser to do anything funny with it. #", "selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), )", "in parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] )", "= node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in classes: class_selector = \".{0}\".format(class_)", "compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully, and", "a list of lists, then do a List.concat # at the end. In", "in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector", "html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO", "string here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts", "html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value))", "t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value):", "is a list type, so simply append to our list of lists items.append(val)", "compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts)", "# does not appear by chance in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element)))", "for part in parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) )", "markers to expression objects, returns a list containing text/expression objects. \"\"\" if not", "text with replacement markers, and a dictionary of replacement markers to expression objects,", "attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope,", "def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in parts)", "\"\"\" HTML specific compilation functions \"\"\" import re import bs4 from fluent.syntax import", "compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes", "return [expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower()", "have any special HTML chars in it # that would cause the HTML", "elm_fluent import compiler items = [] for node in nodes: if isinstance(node, bs4.element.NavigableString):", "parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects,", "retval is not self: return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and", "isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) )", "from fluent.syntax import ast from elm_fluent import codegen from elm_fluent.stubs import defaults as", "expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in", "return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings))", "tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p,", "element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with", "ast from elm_fluent import codegen from elm_fluent.stubs import defaults as dtypes, html, html_attributes", "dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements =", "a string with replacement markers and a dictionary of replacement info \"\"\" parts", ") ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name)", "cases the List.concat will disappear after # simplify. from elm_fluent import compiler items", "classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)): for class_ in classes: class_selector =", "assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = [] for attr_name, attr_value in", "if isinstance(attr_value, list): # Bs4 treats class attribute differently, returns a list, which", "if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items =", "is not self: return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr,", "is_static_only(attr_value): parts = interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in parts) classes", "return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\"", "from elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern,", "else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, )", "ast.Expression objects, returns a string with replacement markers and a dictionary of replacement", "html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes,", "\"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env):", "splitter.split(text) if p] return [expr_replacements.get(t, t) for t in split_text] def get_selectors_for_node(node, expr_replacements):", "and a dictionary of replacement info \"\"\" parts = [] expr_replacements = {}", "isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ),", "so simply append to our list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply(", "node.attrs.get(\"id\", None) if id is not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield", "list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply(", "text/expression objects. \"\"\" if not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter =", "item.expr.name) == \"Html.text\" ) ) new_items = [] for item in self.items: if", "treats class attribute differently, returns a list, which we convert # back to", "all(isinstance(p, str) for p in parts) classes = node.attrs.get(\"class\", []) if is_static_only(\" \".join(classes)):", "our list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) )", "list type, so simply append to our list of lists items.append(val) else: val", "parts = interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part, str): items.append( HtmlList(", "failures gracefully, and check the parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton),", "to do anything funny with it. # TODO - some mechanism that would", "This is a list type, so simply append to our list of lists", "# We have to structure this as a list of lists, then do", "compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes = []", "else: new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def", "re import bs4 from fluent.syntax import ast from elm_fluent import codegen from elm_fluent.stubs", "element in elements: if isinstance(element, ast.TextElement): parts.append(element.value) else: # Need a replacement that", "None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name + id_selector for", "# TODO - handle parse failures gracefully, and check the parser is ensuring", "tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]:", "compile_pattern(pattern, local_scope, compiler_env): skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse failures", "self: return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and", "sorted(node.attrs.items()): if isinstance(attr_value, list): # Bs4 treats class attribute differently, returns a list,", "new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self,", "it # that would cause the HTML parser to do anything funny with", "( len(new_items) > 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if", "then do a List.concat # at the end. In many cases the List.concat", "self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts):", "= codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children),", "a string here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements )", "node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class", "in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ] else: attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name))", "is not None and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name +", "= replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully, and check the parser", "convert # back to a string here: attr_value = \" \".join(attr_value) attr_value_parts =", "= \".{0}\".format(class_) yield class_selector yield tag_name + class_selector id = node.attrs.get(\"id\", None) if", "end. In many cases the List.concat will disappear after # simplify. from elm_fluent", "# back to a string here: attr_value = \" \".join(attr_value) attr_value_parts = interpolate_replacements(", "last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal =", "class_selector id = node.attrs.get(\"id\", None) if id is not None and is_static_only(id): id_selector", "\"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items = [] for item in self.items:", "node in nodes: if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in", "if retval is not self: return retval def is_html_text_call(item): return ( isinstance(item, codegen.FunctionCall)", "[codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if", "the parser is ensuring # well-formedness dom = bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children),", "= interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in parts) classes = node.attrs.get(\"class\",", "= super(HtmlList, self).simplify(changes) if retval is not self: return retval def is_html_text_call(item): return", "- some mechanism that would guarantee this generated string # does not appear", ") ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes =", "for class_ in classes: class_selector = \".{0}\".format(class_) yield class_selector yield tag_name + class_selector", "with it. # TODO - some mechanism that would guarantee this generated string", "a list containing text/expression objects. \"\"\" if not expr_replacements: return [text] replacement_strings =", "attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env ), local_scope, compiler_env, ) ) attr_final_value =", "in the actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts),", "a text with replacement markers, and a dictionary of replacement markers to expression", "returns a list, which we convert # back to a string here: attr_value", "bs4.BeautifulSoup(\"<root>{0}</root>\".format(skeleton), \"lxml\").find(\"root\") return dom_nodes_to_elm( list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope,", "lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert", "= [p for p in splitter.split(text) if p] return [expr_replacements.get(t, t) for t", "parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement", "[] for item in self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1]) and", "special HTML chars in it # that would cause the HTML parser to", "else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items)", "def get_selectors_for_node(node, expr_replacements): tag_name = node.name.lower() yield tag_name def is_static_only(attr_value): parts = interpolate_replacements(attr_value,", "expr_replacements, local_scope, compiler_env): # We have to structure this as a list of", "replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression objects, returns a string with replacement", "= node.name.lower() static_attributes = [] for attr_name, attr_value in sorted(node.attrs.items()): if isinstance(attr_value, list):", "- handle parse failures gracefully, and check the parser is ensuring # well-formedness", "disappear after # simplify. from elm_fluent import compiler items = [] for node", "and a dictionary of replacement markers to expression objects, returns a list containing", "attr_constructor = local_scope.variables[ \"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map(", "local_scope, compiler_env, ) ) attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor =", "node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items)", "list(dom.children), expr_replacements, local_scope, compiler_env ) def dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have", "dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes", "interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part, str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply(", "list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else:", "if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr( part, local_scope, compiler_env", "compiler items = [] for node in nodes: if isinstance(node, bs4.element.NavigableString): parts =", "Given a list of ast.Expression objects, returns a string with replacement markers and", "changes.append(True) else: new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList", "with replacement markers and a dictionary of replacement info \"\"\" parts = []", "simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval is not self: return retval", "\".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for part in", "= [] for item in self.items: if ( len(new_items) > 0 and is_html_text_call(new_items[-1])", "= local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List):", "local_scope, compiler_env ) if tag_name in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor =", "\"\"\" import re import bs4 from fluent.syntax import ast from elm_fluent import codegen", "skeleton, expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully, and check", "# Need a replacement that doesn't have any special HTML chars in it", "doesn't have any special HTML chars in it # that would cause the", "= element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text", "\"Attributes.attribute\" ].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements),", "not expr_replacements: return [text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r", "info \"\"\" parts = [] expr_replacements = {} for element in elements: if", "append to our list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope,", "funny with it. # TODO - some mechanism that would guarantee this generated", "( isinstance(item, codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" )", "class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval is not", "splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) ) split_text = [p for", "it. # TODO - some mechanism that would guarantee this generated string #", "and is_static_only(id): id_selector = \"#{0}\".format(id) yield id_selector yield tag_name + id_selector for attr_name,", "= local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item]))", "= \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector = '[{0}=\"{1}\"]'.format(attr_name,", "to our list of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env)", "of lists items.append(val) else: val = local_scope.variables[\"Html.text\"].apply( compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else:", "string # does not appear by chance in the actual message. replacement_name =", "expr_replacements = replace_non_text_expressions(pattern.elements) # TODO - handle parse failures gracefully, and check the", "expression objects, returns a list containing text/expression objects. \"\"\" if not expr_replacements: return", ") dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([])", "List.concat will disappear after # simplify. from elm_fluent import compiler items = []", "attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector yield tag_name + attr_present_selector if is_static_only(attr_value): attr_value_selector =", "self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def", ") ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes", "local_scope, compiler_env) if val.type == html_output_type: # This is a list type, so", "actual message. replacement_name = \"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def", "\"SSS{0}EEE\".format(str(id(element))) expr_replacements[replacement_name] = element parts.append(replacement_name) return \"\".join(parts), expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given", "of replacement markers to expression objects, returns a list containing text/expression objects. \"\"\"", "many cases the List.concat will disappear after # simplify. from elm_fluent import compiler", "= compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: # This is a list", "dtypes.List.specialize(a=html.Attribute), ) sub_items = dom_nodes_to_elm( list(node.children), expr_replacements, local_scope, compiler_env ) if tag_name in", "replacement info \"\"\" parts = [] expr_replacements = {} for element in elements:", "and is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])]", "else: val = compiler.compile_expr(part, local_scope, compiler_env) if val.type == html_output_type: # This is", "if isinstance(node, bs4.element.NavigableString): parts = interpolate_replacements(str(node), expr_replacements) for part in parts: if isinstance(part,", "would guarantee this generated string # does not appear by chance in the", "guarantee this generated string # does not appear by chance in the actual", "local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def", "in it # that would cause the HTML parser to do anything funny", "codegen from elm_fluent.stubs import defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def", "interpolate_replacements(attr_value, expr_replacements) return all(isinstance(p, str) for p in parts) classes = node.attrs.get(\"class\", [])", "import defaults as dtypes, html, html_attributes html_output_type = dtypes.List.specialize(a=html.Html) def compile_pattern(pattern, local_scope, compiler_env):", "__init__(self, parts): super(HtmlListConcat, self).__init__(parts, html_output_type) def replace_non_text_expressions(elements): \"\"\" Given a list of ast.Expression", "yield tag_name + id_selector for attr_name, attr_value in sorted(node.attrs.items()): if attr_name in [\"id\",", "expr_replacements), ) ) ) dynamic_attributes = local_scope.variables[ \"Fluent.selectAttributes\" ].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else:", "codegen.FunctionCall) and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items", "dom_nodes_to_elm(nodes, expr_replacements, local_scope, compiler_env): # We have to structure this as a list", "and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args", "attr_value in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield", "list of ast.Expression objects, returns a string with replacement markers and a dictionary", "p in splitter.split(text) if p] return [expr_replacements.get(t, t) for t in split_text] def", "expr_replacements def interpolate_replacements(text, expr_replacements): \"\"\" Given a text with replacement markers, and a", ") else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes], dtypes.List.specialize(a=html.Attribute), ) sub_items", "a list type, so simply append to our list of lists items.append(val) else:", "in html.ELEMENTS: node_constructor = local_scope.variables[\"Html.{0}\".format(tag_name)] else: node_constructor = local_scope.variables[\"Html.node\"].apply( codegen.String(tag_name) ) item =", "\"Html.text\" ) ) new_items = [] for item in self.items: if ( len(new_items)", "Bs4 treats class attribute differently, returns a list, which we convert # back", "].apply(codegen.String(attr_name)) static_attributes.append(attr_constructor.apply(attr_final_value)) if compiler_env.dynamic_html_attributes: selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), )", "[codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item) self.items = new_items return self class HtmlListConcat(codegen.ListConcat): literal", "].apply( local_scope.variables[compiler.ATTRS_ARG_NAME], selectors_for_node ) else: dynamic_attributes = codegen.List([]) attributes = codegen.ListConcat( [codegen.List(static_attributes), dynamic_attributes],", "local_scope, compiler_env): # We have to structure this as a list of lists,", "= new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args = [codegen.StringConcat([last_item.args[0]])] last_item.args[0].parts.append(item.args[0]) changes.append(True) else: new_items.append(item)", "mechanism that would guarantee this generated string # does not appear by chance", "compiler.render_to_string(val, local_scope, compiler_env) ) items.append(HtmlList([val])) else: assert isinstance(node, bs4.element.Tag) tag_name = node.name.lower() static_attributes", "\".{0}\".format(class_) yield class_selector yield tag_name + class_selector id = node.attrs.get(\"id\", None) if id", "changes): retval = super(HtmlList, self).simplify(changes) if retval is not self: return retval def", "items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if", "[text] replacement_strings = list(expr_replacements.keys()) splitter = re.compile( \"({0})\".format(\"|\".join(re.escape(r) for r in replacement_strings)) )", "is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0], codegen.StringConcat): last_item.args =", "replacement_strings)) ) split_text = [p for p in splitter.split(text) if p] return [expr_replacements.get(t,", "selectors_for_node = codegen.List( list( map( codegen.String, get_selectors_for_node(node, expr_replacements), ) ) ) dynamic_attributes =", "str): items.append( HtmlList( [ local_scope.variables[\"Html.text\"].apply( codegen.String(str(part)) ) ] ) ) else: val =", ") attr_output_parts = [] for part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else:", "in sorted(node.attrs.items()): if attr_name in [\"id\", \"class\"]: continue attr_present_selector = \"[{0}]\".format(attr_name) yield attr_present_selector", "the HTML parser to do anything funny with it. # TODO - some", "HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self, changes): retval = super(HtmlList, self).simplify(changes) if retval is", ") attr_final_value = codegen.StringConcat(attr_output_parts) if attr_name in html_attributes.ATTRIBUTES: attr_constructor = local_scope.variables[ \"Attributes.{0}\".format(attr_name) ]", "and isinstance(item.expr, codegen.VariableReference) and ( \"{0}.{1}\".format(item.expr.module_name, item.expr.name) == \"Html.text\" ) ) new_items =", "part in attr_value_parts: if isinstance(part, str): attr_output_parts.append(codegen.String(str(part))) else: with compiler_env.modified(html_context=False): attr_output_parts.append( compiler.render_to_string( compiler.compile_expr(", "codegen.String(tag_name) ) item = node_constructor.apply(attributes, sub_items) items.append(HtmlList([item])) return HtmlListConcat(items) class HtmlList(codegen.List): def simplify(self,", "# This is a list type, so simply append to our list of", "== html_output_type: # This is a list type, so simply append to our", "= new_items return self class HtmlListConcat(codegen.ListConcat): literal = HtmlList def __init__(self, parts): super(HtmlListConcat,", "\"\"\" Given a text with replacement markers, and a dictionary of replacement markers", "> 0 and is_html_text_call(new_items[-1]) and is_html_text_call(item) ): last_item = new_items[-1] if not isinstance(last_item.args[0],", "= \" \".join(attr_value) attr_value_parts = interpolate_replacements( attr_value, expr_replacements ) attr_output_parts = [] for", "for r in replacement_strings)) ) split_text = [p for p in splitter.split(text) if" ]
[ "Path, ) -> None: \"\"\"It should be able to create a JSON file", "actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine,", "runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, )", "import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, )", "opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner,", "protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return await", "HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware)", "Path from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from", "ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, PythonFileRunner)", "-> None: \"\"\"It should be able to create a JSON file runner.\"\"\" protocol_file", "test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should be able to", "pytest from pathlib import Path from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine", "= ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result,", "python_protocol_file: Path, ) -> None: \"\"\"It should be able to create a Python", "isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It", "ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should be able to create a", "file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine,", "as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile,", ") assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) ->", "import Path from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine", "factory.\"\"\" import pytest from pathlib import Path from opentrons.hardware_control import API as HardwareAPI", "\"\"\"It should be able to create a Python file runner.\"\"\" protocol_file = ProtocolFile(", "import pytest from pathlib import Path from opentrons.hardware_control import API as HardwareAPI from", "protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should be able to create", "to create a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result", "be able to create a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file,", "protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert", "json_protocol_file: Path, ) -> None: \"\"\"It should be able to create a JSON", "able to create a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, )", "ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def", "( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) ->", "pathlib import Path from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine,", "= create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine,", "-> None: \"\"\"It should be able to create a Python file runner.\"\"\" protocol_file", "able to create a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, )", "PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual", "async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should be", "file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async", "create_protocol_runner factory.\"\"\" import pytest from pathlib import Path from opentrons.hardware_control import API as", "create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should", "\"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner(", "a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner(", "\"\"\"Tests for the create_protocol_runner factory.\"\"\" import pytest from pathlib import Path from opentrons.hardware_control", "from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def", "API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType,", "None: \"\"\"It should be able to create a JSON file runner.\"\"\" protocol_file =", ") -> None: \"\"\"It should be able to create a Python file runner.\"\"\"", "from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner", "Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file,", "should be able to create a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON,", "to create a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result", "from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner,", "assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None:", "JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should", "HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner,", "ProtocolEngine, create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture", "@pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test", "ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner)", "should be able to create a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON,", "opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import", "return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None:", "JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file,", "def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should be able", "create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file:", "from pathlib import Path from opentrons.hardware_control import API as HardwareAPI from opentrons.protocol_engine import", "def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should be able", "-> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async", "create_protocol_engine from opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async", "an actual ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine:", "protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should be able to create", "runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, )", "create a Python file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result =", "smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, )", "test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should be able to", "import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI)", "\"\"\"It should be able to create a JSON file runner.\"\"\" protocol_file = ProtocolFile(", ") -> None: \"\"\"It should be able to create a JSON file runner.\"\"\"", "= ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result,", "the create_protocol_runner factory.\"\"\" import pytest from pathlib import Path from opentrons.hardware_control import API", "file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine,", "None: \"\"\"It should be able to create a Python file runner.\"\"\" protocol_file =", "ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It should be able to create a", "file_path=json_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def", ") result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner(", "ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get", "async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\"", "be able to create a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file,", "async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, ) -> None: \"\"\"It should be", "import API as HardwareAPI from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine from opentrons.file_runner import (", "def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for smoke-test purposes.\"\"\" return", "a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result = create_file_runner(", "opentrons.file_runner import ( ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware:", "create a JSON file runner.\"\"\" protocol_file = ProtocolFile( file_type=ProtocolFileType.JSON, file_path=json_protocol_file, ) result =", "engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path, )", "protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine: ProtocolEngine, python_protocol_file: Path,", "JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an", "ProtocolEngine for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file:", "for smoke-test purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path,", "ProtocolFileType, ProtocolFile, JsonFileRunner, PythonFileRunner, create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine:", "Path, ) -> None: \"\"\"It should be able to create a Python file", "purposes.\"\"\" return await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) ->", "protocol_file = ProtocolFile( file_type=ProtocolFileType.PYTHON, file_path=python_protocol_file, ) result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert", ") @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine for", "result = create_file_runner( protocol_file=protocol_file, engine=protocol_engine, ) assert isinstance(result, JsonFileRunner) async def test_create_python_runner( protocol_engine:", "create_file_runner, ) @pytest.fixture async def protocol_engine(hardware: HardwareAPI) -> ProtocolEngine: \"\"\"Get an actual ProtocolEngine", "for the create_protocol_runner factory.\"\"\" import pytest from pathlib import Path from opentrons.hardware_control import", "await create_protocol_engine(hardware=hardware) async def test_create_json_runner( protocol_engine: ProtocolEngine, json_protocol_file: Path, ) -> None: \"\"\"It" ]
[ "答案是: The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star in, 答案是: Harriet", "Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen", "import random import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966'", "random import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def", "print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in Before the", "in The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin", "unittest import requests import time, os import json import base64 import random import", "Spy|The Scribbler what does [Helen Mack] star in The Son of Kong|Kiss and", "Harriet the Spy', '问题是:what does <NAME> star in, 答案是: The Son of Kong',", "did Michelle Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what does <NAME> star", "test_api.py # @Author: # @Desc : 测试 import unittest import requests import time,", ": 测试 import unittest import requests import time, os import json import base64", "#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2022/4/18 11:45 上午", "[Joe Thomas] appears in which movies The Inbetweeners Movie|The Inbetweeners 2 what films", "result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does", "what films did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The", "act in'], ] params = {'data':data} headers = {'content-type': 'application/json'} r = requests.post(url,", "appears in which movies, 答案是: The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg", "-*- coding: utf-8 -*- # @Date : 2022/4/18 11:45 上午 # @File :", "utf-8 -*- # @Date : 2022/4/18 11:45 上午 # @File : test_api.py #", "star in The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire", "what does [Grégoire Colin] appear in Before the Rain [Joe Thomas] appears in", "Colin] appear in Before the Rain [Joe Thomas] appears in which movies The", "\"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in", "-*- # @Date : 2022/4/18 11:45 上午 # @File : test_api.py # @Author:", "[Helen Mack] star in The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what", "def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in Before the Rain", "appear in, 答案是: Before the Rain', '问题是:NE appears in which movies, 答案是: The", "Princess|Harriet the Spy|The Scribbler what does [Helen Mack] star in The Son of", "'what films did NE star in'], ['<NAME>', 'what does NE star in'], ['<NAME>',", "Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what does <NAME> star in, 答案是:", "in, 答案是: Harriet the Spy', '问题是:what does <NAME> star in, 答案是: The Son", "2022/4/18 11:45 上午 # @File : test_api.py # @Author: # @Desc : 测试", "act in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>',", "['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what films did NE star in'],", "json import base64 import random import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase):", "appear in Before the Rain [Joe Thomas] appears in which movies The Inbetweeners", "Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear in, 答案是: Before", "\"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE appear in'],", "Colin appear in, 答案是: Before the Rain', '问题是:NE appears in which movies, 答案是:", "['<NAME>', 'what films did NE star in'], ['<NAME>', 'what does NE star in'],", "# @Desc : 测试 import unittest import requests import time, os import json", "did Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data", "Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [", "does [Helen Mack] star in The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return:", "films did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler", "requests import time, os import json import base64 import random import string import", "\"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers", "'问题是:NE appears in which movies, 答案是: The Inbetweeners Movie', '问题是:what films did Michelle", "url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE appear in'], ['<NAME>',", "# @Author: # @Desc : 测试 import unittest import requests import time, os", "@Author: # @Desc : 测试 import unittest import requests import time, os import", "in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what", "11:45 上午 # @File : test_api.py # @Author: # @Desc : 测试 import", "Before the Rain [Joe Thomas] appears in which movies The Inbetweeners Movie|The Inbetweeners", "= f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE", "which movies'], ['<NAME>', 'what films did NE star in'], ['<NAME>', 'what does NE", "star in'], ['<NAME>', 'what films did NE act in'], ] params = {'data':data}", "import base64 import random import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server", "[ ['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE appears in which movies'],", "did NE act in'], ] params = {'data':data} headers = {'content-type': 'application/json'} r", "None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear", "the Spy', '问题是:what does <NAME> star in, 答案是: The Son of Kong', '问题是:what", "headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code == 200 assert result", "appears in which movies The Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle", "The Son of Kong', '问题是:what films did Shahid Kapoor act in, 答案是: Haider']", "in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what films did NE star", "params = {'data':data} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360)", "Spy', '问题是:what does <NAME> star in, 答案是: The Son of Kong', '问题是:what films", "测试接口 :return: ['问题是:what does Grégoire Colin appear in, 答案是: Before the Rain', '问题是:NE", "import requests import time, os import json import base64 import random import string", "star in'], ['<NAME>', 'what does NE star in'], ['<NAME>', 'what films did NE", "requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code == 200 assert", "Movie', '问题是:what films did Michelle Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what", "LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url =", "2 what films did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the", "= [ ['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE appears in which", "{'data':data} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result =", "答案是: Harriet the Spy', '问题是:what does <NAME> star in, 答案是: The Son of", "did NE star in'], ['<NAME>', 'what does NE star in'], ['<NAME>', 'what films", "r.json() print(result) assert r.status_code == 200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式", "Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear in,", "= {'data':data} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result", "import time, os import json import base64 import random import string import pickle", "films did NE act in'], ] params = {'data':data} headers = {'content-type': 'application/json'}", "200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案", "pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return:", "f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params =", "'NE appears in which movies'], ['<NAME>', 'what films did NE star in'], ['<NAME>',", "in, 答案是: Before the Rain', '问题是:NE appears in which movies, 答案是: The Inbetweeners", "\"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in Before the Rain [Joe Thomas]", "the Rain', '问题是:NE appears in which movies, 答案是: The Inbetweeners Movie', '问题是:what films", "in'], ] params = {'data':data} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers,", "Scribbler what does [Helen Mack] star in The Son of Kong|Kiss and Make-Up|Divorce", "Michelle Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what does <NAME> star in,", "{'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result", "the Rain [Joe Thomas] appears in which movies The Inbetweeners Movie|The Inbetweeners 2", ":return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type':", "= {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result)", "r.status_code == 200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self):", ": test_api.py # @Author: # @Desc : 测试 import unittest import requests import", "['问题是:what does Grégoire Colin appear in, 答案是: Before the Rain', '问题是:NE appears in", "the Spy|The Scribbler what does [Helen Mack] star in The Son of Kong|Kiss", "which movies, 答案是: The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star in,", "Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen Mack] star in The", "appears in which movies'], ['<NAME>', 'what films did NE star in'], ['<NAME>', 'what", "in'], ['<NAME>', 'what films did NE act in'], ] params = {'data':data} headers", "does <NAME> star in, 答案是: The Son of Kong', '问题是:what films did Shahid", "and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear in, 答案是: Before the", "测试数据的正确答案 what does [Grégoire Colin] appear in Before the Rain [Joe Thomas] appears", "Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen Mack] star in The Son", "films did Michelle Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what does <NAME>", "Before the Rain', '问题是:NE appears in which movies, 答案是: The Inbetweeners Movie', '问题是:what", "Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen Mack] star in", "films did Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\"", "in which movies'], ['<NAME>', 'what films did NE star in'], ['<NAME>', 'what does", "Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star in, 答案是: Harriet the Spy',", "# @Date : 2022/4/18 11:45 上午 # @File : test_api.py # @Author: #", "star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen Mack]", "does NE star in'], ['<NAME>', 'what films did NE act in'], ] params", "def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth':", ": 2022/4/18 11:45 上午 # @File : test_api.py # @Author: # @Desc :", "not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin]", "# -*- coding: utf-8 -*- # @Date : 2022/4/18 11:45 上午 # @File", "host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\"", "films did NE star in'], ['<NAME>', 'what does NE star in'], ['<NAME>', 'what", "in'], ['<NAME>', 'what does NE star in'], ['<NAME>', 'what films did NE act", "答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does", "Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice", "<NAME> star in, 答案是: The Son of Kong', '问题是:what films did Shahid Kapoor", "'问题是:what does <NAME> star in, 答案是: The Son of Kong', '问题是:what films did", "r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code ==", "assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what", "appear in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what films did NE", "Grégoire Colin appear in, 答案是: Before the Rain', '问题是:NE appears in which movies,", "\"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result =", "in, 答案是: The Son of Kong', '问题是:what films did Shahid Kapoor act in,", "NE star in'], ['<NAME>', 'what films did NE act in'], ] params =", "'what does NE appear in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what", "which movies The Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg] star", "{'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert", "headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json()", "star in, 答案是: The Son of Kong', '问题是:what films did Shahid Kapoor act", "what does [Helen Mack] star in The Son of Kong|Kiss and Make-Up|Divorce 测试接口", "'问题是:what films did Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url =", "Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE", "] params = {'data':data} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params),", "= f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url,", "sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\"", "import unittest import requests import time, os import json import base64 import random", "'问题是:what films did Michelle Trachtenberg star in, 答案是: Harriet the Spy', '问题是:what does", "NE star in'], ['<NAME>', 'what does NE star in'], ['<NAME>', 'what films did", "'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code", "Thomas] appears in which movies The Inbetweeners Movie|The Inbetweeners 2 what films did", "['<NAME>', 'what does NE star in'], ['<NAME>', 'what films did NE act in'],", "@Desc : 测试 import unittest import requests import time, os import json import", "test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"}", "['<NAME>', 'what films did NE act in'], ] params = {'data':data} headers =", "in which movies The Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg]", "of Kong', '问题是:what films did Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\"", "NE act in'], ] params = {'data':data} headers = {'content-type': 'application/json'} r =", "Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear in, 答案是: Before the Rain',", ":return: ['问题是:what does Grégoire Colin appear in, 答案是: Before the Rain', '问题是:NE appears", "movies'], ['<NAME>', 'what films did NE star in'], ['<NAME>', 'what does NE star", "['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>',", "timeout=360) result = r.json() print(result) assert r.status_code == 200 assert result is not", "of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear in, 答案是:", "params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params),", "class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url", "答案是: The Son of Kong', '问题是:what films did Shahid Kapoor act in, 答案是:", "f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers,", "[Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does", "assert r.status_code == 200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def", "movies, 答案是: The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star in, 答案是:", "Son of Kong', '问题是:what films did Shahid Kapoor act in, 答案是: Haider'] :rtype:", "data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code == 200 assert result is", "movies The Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg] star in", "'what does NE star in'], ['<NAME>', 'what films did NE act in'], ]", "= f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params", "\"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r", "in Before the Rain [Joe Thomas] appears in which movies The Inbetweeners Movie|The", "The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does Grégoire Colin appear", "The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star in, 答案是: Harriet the", "import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self):", "= r.json() print(result) assert r.status_code == 200 assert result is not None, \"返回结果为None\"", "Inbetweeners 2 what films did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet", "答案是: Before the Rain', '问题是:NE appears in which movies, 答案是: The Inbetweeners Movie',", "in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what does [Helen Mack] star", "is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire", "import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口", "= requests.post(url, headers=headers, data=json.dumps(params), timeout=360) result = r.json() print(result) assert r.status_code == 200", "python # -*- coding: utf-8 -*- # @Date : 2022/4/18 11:45 上午 #", "did [Michelle Trachtenberg] star in Inspector Gadget|Black Christmas|Ice Princess|Harriet the Spy|The Scribbler what", "url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r =", "上午 # @File : test_api.py # @Author: # @Desc : 测试 import unittest", "test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in Before the Rain [Joe", "base64 import random import string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server =", "Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data =", "string import pickle import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\"", "# @File : test_api.py # @Author: # @Desc : 测试 import unittest import", "does Grégoire Colin appear in, 答案是: Before the Rain', '问题是:NE appears in which", "== 200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\"", "star in, 答案是: Harriet the Spy', '问题是:what does <NAME> star in, 答案是: The", "os import json import base64 import random import string import pickle import sys", "does NE appear in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what films", "[Grégoire Colin] appear in Before the Rain [Joe Thomas] appears in which movies", "import sys class LSTMKQGATestCase(unittest.TestCase): host_server = f'http://l8:9966' def test_lstmkgqa_file(self): \"\"\" 测试文件接口 :return: :rtype:", "print(result) assert r.status_code == 200 assert result is not None, \"返回结果为None\" #检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\")", "= {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'} r = requests.post(url, headers=headers, data=json.dumps(params), timeout=360)", ":rtype: \"\"\" url = f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE appear", "f\"{self.host_server}/api/predict\" data = [ ['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE appears", "The Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg] star in Inspector", "测试 import unittest import requests import time, os import json import base64 import", "Mack] star in The Son of Kong|Kiss and Make-Up|Divorce 测试接口 :return: ['问题是:what does", "import json import base64 import random import string import pickle import sys class", "@File : test_api.py # @Author: # @Desc : 测试 import unittest import requests", "time, os import json import base64 import random import string import pickle import", "Inbetweeners Movie|The Inbetweeners 2 what films did [Michelle Trachtenberg] star in Inspector Gadget|Black", "Kong', '问题是:what films did Shahid Kapoor act in, 答案是: Haider'] :rtype: \"\"\" url", "result = r.json() print(result) assert r.status_code == 200 assert result is not None,", "in which movies, 答案是: The Inbetweeners Movie', '问题是:what films did Michelle Trachtenberg star", "@Date : 2022/4/18 11:45 上午 # @File : test_api.py # @Author: # @Desc", "#检查结果,里面肯定是字典格式 print(\"对文件接口测试完成\") def test_lstmkgqa(self): \"\"\" 测试数据的正确答案 what does [Grégoire Colin] appear in Before", "does [Grégoire Colin] appear in Before the Rain [Joe Thomas] appears in which", "NE appear in'], ['<NAME>', 'NE appears in which movies'], ['<NAME>', 'what films did", "'what films did NE act in'], ] params = {'data':data} headers = {'content-type':", ":rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers = {'content-type': 'application/json'}", "Rain', '问题是:NE appears in which movies, 答案是: The Inbetweeners Movie', '问题是:what films did", "Rain [Joe Thomas] appears in which movies The Inbetweeners Movie|The Inbetweeners 2 what", "coding: utf-8 -*- # @Date : 2022/4/18 11:45 上午 # @File : test_api.py", "data = [ ['<NAME>', 'what does NE appear in'], ['<NAME>', 'NE appears in", "测试文件接口 :return: :rtype: \"\"\" url = f\"{self.host_server}/api/predict_file\" params = {'data_apth': \"./../data/QA_data/MetaQA/qa_test_1hop.txt\"} headers =" ]
[ "flights available if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details", "continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details = flight_data.get_data() data_manger.update_data(city_id, flight_data.min_price) notification_manager.send_alert(flight_details,", "NotificationManager classes to achieve the program requirements. from notification_manager import NotificationManager from flight_search", "FlightData from data_manager import DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data =", "= city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no flights", "data_manger = DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list:", "from notification_manager import NotificationManager from flight_search import FlightSearch from flight_data import FlightData from", "DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger = DataManager()", "flight_search = FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list", "city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no flights available", "from flight_data import FlightData from data_manager import DataManager notification_manager = NotificationManager() flight_search =", "DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list: city_id =", "achieve the program requirements. from notification_manager import NotificationManager from flight_search import FlightSearch from", "if no flights available if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if", "= DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list: city_id", "city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no flights available if not price_data:", "= city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check", "= FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for city", "= NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list =", "lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no", "to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. from", "in destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data =", "from flight_search import FlightSearch from flight_data import FlightData from data_manager import DataManager notification_manager", "from data_manager import DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data = FlightData()", "Check if no flights available if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price)", "fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no flights available if", "import DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger =", "NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list = data_manger.get_users()", "notification_manager import NotificationManager from flight_search import FlightSearch from flight_data import FlightData from data_manager", "= flight_search.get_data(fly_to) # Check if no flights available if not price_data: continue is_cheap_deal", "<gh_stars>0 #This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to", "data_manager import DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger", "for city in destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode']", "import NotificationManager from flight_search import FlightSearch from flight_data import FlightData from data_manager import", "will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program", "FlightSearch from flight_data import FlightData from data_manager import DataManager notification_manager = NotificationManager() flight_search", "user_list = data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list: city_id = city['id']", "city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if", "#This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve", "data_manger.get_data() for city in destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to =", "the program requirements. from notification_manager import NotificationManager from flight_search import FlightSearch from flight_data", "use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. from notification_manager", "need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.", "= FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list =", "city_id = city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to) #", "= city['iataCode'] price_data = flight_search.get_data(fly_to) # Check if no flights available if not", "price_data = flight_search.get_data(fly_to) # Check if no flights available if not price_data: continue", "not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details = flight_data.get_data() data_manger.update_data(city_id,", "flight_search.get_data(fly_to) # Check if no flights available if not price_data: continue is_cheap_deal =", "= data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list: city_id = city['id'] lowest_price", "data_manger.get_users() destination_list = data_manger.get_data() for city in destination_list: city_id = city['id'] lowest_price =", "is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details = flight_data.get_data() data_manger.update_data(city_id, flight_data.min_price) notification_manager.send_alert(flight_details, user_list)", "import FlightData from data_manager import DataManager notification_manager = NotificationManager() flight_search = FlightSearch() flight_data", "NotificationManager from flight_search import FlightSearch from flight_data import FlightData from data_manager import DataManager", "flight_data = FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for", "classes to achieve the program requirements. from notification_manager import NotificationManager from flight_search import", "FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data() for city in", "DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. from notification_manager import NotificationManager", "no flights available if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal:", "to achieve the program requirements. from notification_manager import NotificationManager from flight_search import FlightSearch", "flight_data import FlightData from data_manager import DataManager notification_manager = NotificationManager() flight_search = FlightSearch()", "flight_search import FlightSearch from flight_data import FlightData from data_manager import DataManager notification_manager =", "requirements. from notification_manager import NotificationManager from flight_search import FlightSearch from flight_data import FlightData", "FlightData, NotificationManager classes to achieve the program requirements. from notification_manager import NotificationManager from", "price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details = flight_data.get_data() data_manger.update_data(city_id, flight_data.min_price)", "city in destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data", "program requirements. from notification_manager import NotificationManager from flight_search import FlightSearch from flight_data import", "notification_manager = NotificationManager() flight_search = FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list", "available if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details =", "= data_manger.get_data() for city in destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to", "destination_list: city_id = city['id'] lowest_price = city['lowestPrice'] fly_to = city['iataCode'] price_data = flight_search.get_data(fly_to)", "FlightSearch() flight_data = FlightData() data_manger = DataManager() user_list = data_manger.get_users() destination_list = data_manger.get_data()", "the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. from notification_manager import", "import FlightSearch from flight_data import FlightData from data_manager import DataManager notification_manager = NotificationManager()", "if not price_data: continue is_cheap_deal = flight_data.compare(price_data, lowest_price) if is_cheap_deal: flight_details = flight_data.get_data()", "# Check if no flights available if not price_data: continue is_cheap_deal = flight_data.compare(price_data,", "destination_list = data_manger.get_data() for city in destination_list: city_id = city['id'] lowest_price = city['lowestPrice']", "file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the" ]
[ "<reponame>cltl/FrameNetNLTK<gh_stars>1-10 import sys sys.path.insert(0, '../..') from FrameNetNLTK import load my_fn = load(folder='test_lexicon', verbose=2)" ]
[ "-- amplitude in lift phase center_extension -- center of leg extension \"\"\" stance_lift_cutoff", "new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI) extensions = []", "TG and parameters. Args: phase: a number in [0, 2pi) representing current leg", "import division from __future__ import print_function import math import numpy as np TWO_PI", "- stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi)", "trajectory generator. Args: current_phases: phases of each leg. leg_frequencies: the frequency to proceed", "stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where(", "Args: current_phases: phases of each leg. leg_frequencies: the frequency to proceed the phase", "generator. Args: current_phases: phases of each leg. leg_frequencies: the frequency to proceed the", "np.pi + (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase /", "leg extension given current phase of TG and parameters. Args: phase: a number", "of each leg. dt: amount of time (sec) between consecutive time steps. tg_params:", "leg_frequencies * dt, TWO_PI) extensions = [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[...,", "math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current phase of TG", "leg phase tg_params: a dictionary of tg parameters: stance_lift_cutoff -- switches the TG", "current phase of TG and parameters. Args: phase: a number in [0, 2pi)", "leg. dt: amount of time (sec) between consecutive time steps. tg_params: a set", "-- amplitude in swing phase amplitude_lift -- amplitude in lift phase center_extension --", "[0, 2pi) representing current leg phase tg_params: a dictionary of tg parameters: stance_lift_cutoff", "(phase < cutoff) and lift (phase > cutoff) phase amplitude_swing -- amplitude in", "center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff,", "tg_params): \"\"\"Steps forward the in-place trajectory generator. Args: current_phases: phases of each leg.", "the trajectory generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI *", "dictionary of tg parameters: stance_lift_cutoff -- switches the TG between stance (phase <", "actions: leg swing/extensions as output by the trajectory generator. new_state: new swing/extension. \"\"\"", "absolute_import from __future__ import division from __future__ import print_function import math import numpy", "phase amplitude_lift -- amplitude in lift phase center_extension -- center of leg extension", "a dictionary of tg parameters: stance_lift_cutoff -- switches the TG between stance (phase", "= np.where( phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI -", "TWO_PI) extensions = [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return", "* leg_frequencies * dt, TWO_PI) extensions = [] for leg_id in range(4): extensions.append(", "trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions", "phase tg_params: a dictionary of tg parameters: stance_lift_cutoff -- switches the TG between", "new_phases, extensions def reset(): return np.array([0, np.pi * 0.5, np.pi, np.pi * 1.5])", "in lift phase center_extension -- center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff']", "Generator for in-place stepping motion for quadruped robot.\"\"\" from __future__ import absolute_import from", "for in-place stepping motion for quadruped robot.\"\"\" from __future__ import absolute_import from __future__", "time (sec) between consecutive time steps. tg_params: a set of parameters for trajectory", "for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset():", "between stance (phase < cutoff) and lift (phase > cutoff) phase amplitude_swing --", "> stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi,", "(phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff *", "tg_params: a set of parameters for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\"", "range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset(): return np.array([0, np.pi", "division from __future__ import print_function import math import numpy as np TWO_PI =", "stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase", "phase of TG and parameters. Args: phase: a number in [0, 2pi) representing", "leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory generator. Args: current_phases: phases of", "-- center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase <", "\"\"\"Trajectory Generator for in-place stepping motion for quadruped robot.\"\"\" from __future__ import absolute_import", "phase amplitude_swing -- amplitude in swing phase amplitude_lift -- amplitude in lift phase", "phases of each leg. leg_frequencies: the frequency to proceed the phase of each", "/ stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies,", "as np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg", "np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension", "cutoff) phase amplitude_swing -- amplitude in swing phase amplitude_lift -- amplitude in lift", "output by the trajectory generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases +", "parameters for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions:", "* dt, TWO_PI) extensions = [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id],", "import absolute_import from __future__ import division from __future__ import print_function import math import", "= 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current", "leg. leg_frequencies: the frequency to proceed the phase of each leg. dt: amount", "swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI) extensions", "= [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions", "center_extension -- center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase", "stance_lift_cutoff -- switches the TG between stance (phase < cutoff) and lift (phase", "< cutoff) and lift (phase > cutoff) phase amplitude_swing -- amplitude in swing", "leg_id], tg_params)) return new_phases, extensions def reset(): return np.array([0, np.pi * 0.5, np.pi,", "_get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current phase of TG and parameters.", "np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI) extensions = [] for leg_id", "- stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime", "_get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset(): return np.array([0, np.pi * 0.5,", "extension given current phase of TG and parameters. Args: phase: a number in", "amplitude in lift phase center_extension -- center of leg extension \"\"\" stance_lift_cutoff =", "and parameters. Args: phase: a number in [0, 2pi) representing current leg phase", "trajectory generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies", "of tg parameters: stance_lift_cutoff -- switches the TG between stance (phase < cutoff)", "from __future__ import print_function import math import numpy as np TWO_PI = 2", "amplitude_swing -- amplitude in swing phase amplitude_lift -- amplitude in lift phase center_extension", "def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory generator. Args: current_phases:", "import numpy as np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns", "swing phase amplitude_lift -- amplitude in lift phase center_extension -- center of leg", "np.where( phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff)", "current_phases: phases of each leg. leg_frequencies: the frequency to proceed the phase of", "for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg", "leg swing/extensions as output by the trajectory generator. new_state: new swing/extension. \"\"\" new_phases", "amplitude in swing phase amplitude_lift -- amplitude in lift phase center_extension -- center", "the frequency to proceed the phase of each leg. dt: amount of time", "dt: amount of time (sec) between consecutive time steps. tg_params: a set of", "numpy as np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the", "steps. tg_params: a set of parameters for trajectory generator, see the docstring of", "\"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as output by the trajectory generator.", "extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset(): return np.array([0, np.pi *", "consecutive time steps. tg_params: a set of parameters for trajectory generator, see the", "step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory generator. Args: current_phases: phases", "and lift (phase > cutoff) phase amplitude_swing -- amplitude in swing phase amplitude_lift", "docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as output by the", "TG between stance (phase < cutoff) and lift (phase > cutoff) phase amplitude_swing", "tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff)", "import math import numpy as np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase,", "robot.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function", "stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi) return", "by the trajectory generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI", "parameters: stance_lift_cutoff -- switches the TG between stance (phase < cutoff) and lift", "of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'],", "extensions = [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases,", "= np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI) extensions = [] for", "np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps", "/ (TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension']", "* np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params):", "time steps. tg_params: a set of parameters for trajectory generator, see the docstring", "for details. Returns: actions: leg swing/extensions as output by the trajectory generator. new_state:", "in [0, 2pi) representing current leg phase tg_params: a dictionary of tg parameters:", "(sec) between consecutive time steps. tg_params: a set of parameters for trajectory generator,", "in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset(): return np.array([0,", "generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies *", "np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory generator. Args:", "extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase", "from __future__ import division from __future__ import print_function import math import numpy as", "set of parameters for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for details.", "tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) /", "each leg. leg_frequencies: the frequency to proceed the phase of each leg. dt:", "import print_function import math import numpy as np TWO_PI = 2 * math.pi", "amplitude_lift -- amplitude in lift phase center_extension -- center of leg extension \"\"\"", "TWO_PI * leg_frequencies * dt, TWO_PI) extensions = [] for leg_id in range(4):", "a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff,", "math import numpy as np TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params):", "lift phase center_extension -- center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime", "in swing phase amplitude_lift -- amplitude in lift phase center_extension -- center of", "* np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase)", "of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as output by the trajectory", "parameters. Args: phase: a number in [0, 2pi) representing current leg phase tg_params:", "2pi) representing current leg phase tg_params: a dictionary of tg parameters: stance_lift_cutoff --", "* np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory generator.", "the TG between stance (phase < cutoff) and lift (phase > cutoff) phase", "the in-place trajectory generator. Args: current_phases: phases of each leg. leg_frequencies: the frequency", "\"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI) extensions =", "leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift'])", "swing/extensions as output by the trajectory generator. new_state: new swing/extension. \"\"\" new_phases =", "-- switches the TG between stance (phase < cutoff) and lift (phase >", "+ (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff", "details. Returns: actions: leg swing/extensions as output by the trajectory generator. new_state: new", "of TG and parameters. Args: phase: a number in [0, 2pi) representing current", "leg_frequencies: the frequency to proceed the phase of each leg. dt: amount of", "(TWO_PI - stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] +", "amount of time (sec) between consecutive time steps. tg_params: a set of parameters", "return new_phases, extensions def reset(): return np.array([0, np.pi * 0.5, np.pi, np.pi *", "the leg extension given current phase of TG and parameters. Args: phase: a", "dt, tg_params): \"\"\"Steps forward the in-place trajectory generator. Args: current_phases: phases of each", "* math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current phase of", "in-place trajectory generator. Args: current_phases: phases of each leg. leg_frequencies: the frequency to", "as output by the trajectory generator. new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases", "tg_params)) return new_phases, extensions def reset(): return np.array([0, np.pi * 0.5, np.pi, np.pi", "of time (sec) between consecutive time steps. tg_params: a set of parameters for", "tg_params): \"\"\"Returns the leg extension given current phase of TG and parameters. Args:", "\"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase =", "Args: phase: a number in [0, 2pi) representing current leg phase tg_params: a", "= tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase", "motion for quadruped robot.\"\"\" from __future__ import absolute_import from __future__ import division from", "phase: a number in [0, 2pi) representing current leg phase tg_params: a dictionary", "tg_params['stance_lift_cutoff'] a_prime = np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase >", "phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI - stance_lift_cutoff) *", "+ a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place", "__future__ import division from __future__ import print_function import math import numpy as np", "stepping motion for quadruped robot.\"\"\" from __future__ import absolute_import from __future__ import division", "\"\"\"Steps forward the in-place trajectory generator. Args: current_phases: phases of each leg. leg_frequencies:", "cutoff) and lift (phase > cutoff) phase amplitude_swing -- amplitude in swing phase", "a number in [0, 2pi) representing current leg phase tg_params: a dictionary of", "= np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi", "tg_params: a dictionary of tg parameters: stance_lift_cutoff -- switches the TG between stance", "of parameters for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns:", "phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases,", "Returns: actions: leg swing/extensions as output by the trajectory generator. new_state: new swing/extension.", "phase of each leg. dt: amount of time (sec) between consecutive time steps.", "\"\"\"Returns the leg extension given current phase of TG and parameters. Args: phase:", "tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the", "a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward the in-place trajectory", "quadruped robot.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import", "given current phase of TG and parameters. Args: phase: a number in [0,", "the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as output by", "leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def reset(): return", "representing current leg phase tg_params: a dictionary of tg parameters: stance_lift_cutoff -- switches", "stance (phase < cutoff) and lift (phase > cutoff) phase amplitude_swing -- amplitude", "stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt,", "lift (phase > cutoff) phase amplitude_swing -- amplitude in swing phase amplitude_lift --", "[] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params)) return new_phases, extensions def", "scaled_phase = np.where( phase > stance_lift_cutoff, np.pi + (phase - stance_lift_cutoff) / (TWO_PI", "> cutoff) phase amplitude_swing -- amplitude in swing phase amplitude_lift -- amplitude in", "of each leg. leg_frequencies: the frequency to proceed the phase of each leg.", "< stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi + (phase", "for quadruped robot.\"\"\" from __future__ import absolute_import from __future__ import division from __future__", "proceed the phase of each leg. dt: amount of time (sec) between consecutive", "new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies * dt, TWO_PI)", "in-place stepping motion for quadruped robot.\"\"\" from __future__ import absolute_import from __future__ import", "current leg phase tg_params: a dictionary of tg parameters: stance_lift_cutoff -- switches the", "from __future__ import absolute_import from __future__ import division from __future__ import print_function import", "each leg. dt: amount of time (sec) between consecutive time steps. tg_params: a", "return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def step(current_phases, leg_frequencies, dt, tg_params): \"\"\"Steps forward", "(phase > cutoff) phase amplitude_swing -- amplitude in swing phase amplitude_lift -- amplitude", "stance_lift_cutoff) * np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime *", "def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current phase of TG and", "np.pi, phase / stance_lift_cutoff * np.pi) return tg_params['center_extension'] + a_prime * np.sin(scaled_phase) def", "frequency to proceed the phase of each leg. dt: amount of time (sec)", "to proceed the phase of each leg. dt: amount of time (sec) between", "number in [0, 2pi) representing current leg phase tg_params: a dictionary of tg", "see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as output", "np.where(phase < stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi +", "between consecutive time steps. tg_params: a set of parameters for trajectory generator, see", "stance_lift_cutoff, tg_params['amplitude_stance'], tg_params['amplitude_lift']) scaled_phase = np.where( phase > stance_lift_cutoff, np.pi + (phase -", "TWO_PI = 2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given", "forward the in-place trajectory generator. Args: current_phases: phases of each leg. leg_frequencies: the", "the phase of each leg. dt: amount of time (sec) between consecutive time", "generator, see the docstring of \"_get_actions_asymmetric_sine\" for details. Returns: actions: leg swing/extensions as", "new_state: new swing/extension. \"\"\" new_phases = np.fmod(current_phases + TWO_PI * leg_frequencies * dt,", "+ TWO_PI * leg_frequencies * dt, TWO_PI) extensions = [] for leg_id in", "print_function import math import numpy as np TWO_PI = 2 * math.pi def", "__future__ import absolute_import from __future__ import division from __future__ import print_function import math", "__future__ import print_function import math import numpy as np TWO_PI = 2 *", "2 * math.pi def _get_actions_asymmetric_sine(phase, tg_params): \"\"\"Returns the leg extension given current phase", "tg parameters: stance_lift_cutoff -- switches the TG between stance (phase < cutoff) and", "a set of parameters for trajectory generator, see the docstring of \"_get_actions_asymmetric_sine\" for", "dt, TWO_PI) extensions = [] for leg_id in range(4): extensions.append( _get_actions_asymmetric_sine(new_phases[..., leg_id], tg_params))", "phase center_extension -- center of leg extension \"\"\" stance_lift_cutoff = tg_params['stance_lift_cutoff'] a_prime =", "switches the TG between stance (phase < cutoff) and lift (phase > cutoff)" ]
[ "3 values used to test pythagoras theorem that gives an answer of 5", "agent if random.random() < 0.5: y1 += 1 else: y1 -= 1 if", "((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5 being the square", "this function varies from the random.random function, as the randint functions offers the", "for the x coordinate if random.random() < 0.5: x0 += 1 #increases a", "x1 -= 1 \"\"\" #y0 = 0 #x0 = 0 #y1 = 4", "if random.random() < 0.5: x1 += 1 else: x1 -= 1 \"\"\" #y0", "0-99 x1= random.randint (0,99) #same method as for previous agent if random.random() <", "< 0.5:# generates a random number with a value of 0-0.99 y0 +=", "if random.random() < 0.5: y1 += 1 else: y1 -= 1 if random.random()", "being the square root of c, which is the distance between 1 and", "# imports the random function \"\"\" ransomised position of y coordinate of agent", "randint functions offers the possibility to create a range of numbers whereas random.random", "x direction \"\"\" same action for a second agent\"\"\" y1= random.randint (0,99) #generates", "which is the distance between 1 and 2\"\"\" print (answer)# prints the result", "1 if random.random() < 0.5: x1 += 1 else: x1 -= 1 \"\"\"", "#y0 = 0 #x0 = 0 #y1 = 4 #x1 = 3 values", "random function \"\"\" ransomised position of y coordinate of agent in a 99*99", "#increases a step in the x direction else: x0 -= 1 #decreases a", "#generates a number within the specified parameters in this case 0-99 x1= random.randint", "the y direction else: y0 -= 1 #deccreases a step in the y", "is the distance between 1 and 2\"\"\" print (answer)# prints the result from", "the randomised sequence gives varying answers\"\"\" answer = (((y0 - y1)**2) + ((x0", "function \"\"\" ransomised position of y coordinate of agent in a 99*99 grid,", "0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make Random movement by 1 step", "is the same movement for the x coordinate if random.random() < 0.5: x0", "**0.5 being the square root of c, which is the distance between 1", "range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make Random movement by", "random.random() < 0.5:# generates a random number with a value of 0-0.99 y0", "1 #increases a step in the y direction else: y0 -= 1 #deccreases", "for previous agent if random.random() < 0.5: y1 += 1 else: y1 -=", "offers the possibility to create a range of numbers whereas random.random offers a", "the x coordinate if random.random() < 0.5: x0 += 1 #increases a step", "the square root of c, which is the distance between 1 and 2\"\"\"", "x1= random.randint (0,99) #same method as for previous agent if random.random() < 0.5:", "-= 1 #decreases a step in the x direction \"\"\" same action for", "agent in a 99*99 grid, this function varies from the random.random function, as", "gives an answer of 5 the randomised sequence gives varying answers\"\"\" answer =", "from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make Random movement by 1", "movement by 1 step in the y coordinate if random.random() < 0.5:# generates", "x direction else: x0 -= 1 #decreases a step in the x direction", "#deccreases a step in the y direction #This is the same movement for", "used to test pythagoras theorem that gives an answer of 5 the randomised", "the y coordinate if random.random() < 0.5:# generates a random number with a", "case 0-99 x1= random.randint (0,99) #same method as for previous agent if random.random()", "random.random() < 0.5: x1 += 1 else: x1 -= 1 \"\"\" #y0 =", "x1 += 1 else: x1 -= 1 \"\"\" #y0 = 0 #x0 =", "= 0 #x0 = 0 #y1 = 4 #x1 = 3 values used", "\"\"\"a suared+ b squared= c squared, **0.5 being the square root of c,", "1 #decreases a step in the x direction \"\"\" same action for a", "random.randint (0,99) #generates a number within the specified parameters in this case 0-99", "<reponame>gy19sp/GEO5003-Practicals<gh_stars>0 import random # imports the random function \"\"\" ransomised position of y", "\"\"\" ransomised position of y coordinate of agent in a 99*99 grid, this", "create a range of numbers whereas random.random offers a range from 0-1\"\"\" y0=", "(0,99) x0= random.randint (0,99) #Make Random movement by 1 step in the y", "y0 += 1 #increases a step in the y direction else: y0 -=", "else: x0 -= 1 #decreases a step in the x direction \"\"\" same", "(((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c squared,", "\"\"\" #y0 = 0 #x0 = 0 #y1 = 4 #x1 = 3", "direction #This is the same movement for the x coordinate if random.random() <", "within the specified parameters in this case 0-99 x1= random.randint (0,99) #same method", "answers\"\"\" answer = (((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b", "of y coordinate of agent in a 99*99 grid, this function varies from", "y0 -= 1 #deccreases a step in the y direction #This is the", "answer of 5 the randomised sequence gives varying answers\"\"\" answer = (((y0 -", "in the y direction #This is the same movement for the x coordinate", "the same movement for the x coordinate if random.random() < 0.5: x0 +=", "in the y coordinate if random.random() < 0.5:# generates a random number with", "random.random() < 0.5: y1 += 1 else: y1 -= 1 if random.random() <", "Random movement by 1 step in the y coordinate if random.random() < 0.5:#", "generates a random number with a value of 0-0.99 y0 += 1 #increases", "a step in the x direction \"\"\" same action for a second agent\"\"\"", "x0= random.randint (0,99) #Make Random movement by 1 step in the y coordinate", "coordinate if random.random() < 0.5:# generates a random number with a value of", "0.5: x0 += 1 #increases a step in the x direction else: x0", "#same method as for previous agent if random.random() < 0.5: y1 += 1", "#x0 = 0 #y1 = 4 #x1 = 3 values used to test", "#y1 = 4 #x1 = 3 values used to test pythagoras theorem that", "random number with a value of 0-0.99 y0 += 1 #increases a step", "a step in the y direction #This is the same movement for the", "of agent in a 99*99 grid, this function varies from the random.random function,", "1 else: y1 -= 1 if random.random() < 0.5: x1 += 1 else:", "numbers whereas random.random offers a range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint", "5 the randomised sequence gives varying answers\"\"\" answer = (((y0 - y1)**2) +", "= 4 #x1 = 3 values used to test pythagoras theorem that gives", "0 #x0 = 0 #y1 = 4 #x1 = 3 values used to", "y1 += 1 else: y1 -= 1 if random.random() < 0.5: x1 +=", "+= 1 #increases a step in the x direction else: x0 -= 1", "random.random offers a range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make", "(0,99) #Make Random movement by 1 step in the y coordinate if random.random()", "of numbers whereas random.random offers a range from 0-1\"\"\" y0= random.randint (0,99) x0=", "function varies from the random.random function, as the randint functions offers the possibility", "< 0.5: x0 += 1 #increases a step in the x direction else:", "in this case 0-99 x1= random.randint (0,99) #same method as for previous agent", "the random function \"\"\" ransomised position of y coordinate of agent in a", "the distance between 1 and 2\"\"\" print (answer)# prints the result from the", "random # imports the random function \"\"\" ransomised position of y coordinate of", "random.random() < 0.5: x0 += 1 #increases a step in the x direction", "square root of c, which is the distance between 1 and 2\"\"\" print", "a range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make Random movement", "a range of numbers whereas random.random offers a range from 0-1\"\"\" y0= random.randint", "= 0 #y1 = 4 #x1 = 3 values used to test pythagoras", "a 99*99 grid, this function varies from the random.random function, as the randint", "the possibility to create a range of numbers whereas random.random offers a range", "number within the specified parameters in this case 0-99 x1= random.randint (0,99) #same", "values used to test pythagoras theorem that gives an answer of 5 the", "else: y0 -= 1 #deccreases a step in the y direction #This is", "agent\"\"\" y1= random.randint (0,99) #generates a number within the specified parameters in this", "-= 1 \"\"\" #y0 = 0 #x0 = 0 #y1 = 4 #x1", "(0,99) #generates a number within the specified parameters in this case 0-99 x1=", "+= 1 else: x1 -= 1 \"\"\" #y0 = 0 #x0 = 0", "the randint functions offers the possibility to create a range of numbers whereas", "the x direction \"\"\" same action for a second agent\"\"\" y1= random.randint (0,99)", "y1= random.randint (0,99) #generates a number within the specified parameters in this case", "c squared, **0.5 being the square root of c, which is the distance", "import random # imports the random function \"\"\" ransomised position of y coordinate", "else: y1 -= 1 if random.random() < 0.5: x1 += 1 else: x1", "#Make Random movement by 1 step in the y coordinate if random.random() <", "same movement for the x coordinate if random.random() < 0.5: x0 += 1", "movement for the x coordinate if random.random() < 0.5: x0 += 1 #increases", "suared+ b squared= c squared, **0.5 being the square root of c, which", "as for previous agent if random.random() < 0.5: y1 += 1 else: y1", "coordinate if random.random() < 0.5: x0 += 1 #increases a step in the", "from the random.random function, as the randint functions offers the possibility to create", "y direction else: y0 -= 1 #deccreases a step in the y direction", "position of y coordinate of agent in a 99*99 grid, this function varies", "0.5: y1 += 1 else: y1 -= 1 if random.random() < 0.5: x1", "y coordinate of agent in a 99*99 grid, this function varies from the", "+ ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5 being the", "action for a second agent\"\"\" y1= random.randint (0,99) #generates a number within the", "< 0.5: x1 += 1 else: x1 -= 1 \"\"\" #y0 = 0", "to create a range of numbers whereas random.random offers a range from 0-1\"\"\"", "0.5:# generates a random number with a value of 0-0.99 y0 += 1", "#This is the same movement for the x coordinate if random.random() < 0.5:", "= 3 values used to test pythagoras theorem that gives an answer of", "that gives an answer of 5 the randomised sequence gives varying answers\"\"\" answer", "the specified parameters in this case 0-99 x1= random.randint (0,99) #same method as", "x0 -= 1 #decreases a step in the x direction \"\"\" same action", "\"\"\" same action for a second agent\"\"\" y1= random.randint (0,99) #generates a number", "root of c, which is the distance between 1 and 2\"\"\" print (answer)#", "randomised sequence gives varying answers\"\"\" answer = (((y0 - y1)**2) + ((x0 -", "as the randint functions offers the possibility to create a range of numbers", "ransomised position of y coordinate of agent in a 99*99 grid, this function", "else: x1 -= 1 \"\"\" #y0 = 0 #x0 = 0 #y1 =", "c, which is the distance between 1 and 2\"\"\" print (answer)# prints the", "1 \"\"\" #y0 = 0 #x0 = 0 #y1 = 4 #x1 =", "functions offers the possibility to create a range of numbers whereas random.random offers", "b squared= c squared, **0.5 being the square root of c, which is", "a value of 0-0.99 y0 += 1 #increases a step in the y", "previous agent if random.random() < 0.5: y1 += 1 else: y1 -= 1", "grid, this function varies from the random.random function, as the randint functions offers", "#x1 = 3 values used to test pythagoras theorem that gives an answer", "in a 99*99 grid, this function varies from the random.random function, as the", "varies from the random.random function, as the randint functions offers the possibility to", "= (((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c", "a step in the x direction else: x0 -= 1 #decreases a step", "of c, which is the distance between 1 and 2\"\"\" print (answer)# prints", "4 #x1 = 3 values used to test pythagoras theorem that gives an", "y0= random.randint (0,99) x0= random.randint (0,99) #Make Random movement by 1 step in", "random.randint (0,99) #Make Random movement by 1 step in the y coordinate if", "a step in the y direction else: y0 -= 1 #deccreases a step", "sequence gives varying answers\"\"\" answer = (((y0 - y1)**2) + ((x0 - x1)**2))**0.5", "1 step in the y coordinate if random.random() < 0.5:# generates a random", "answer = (((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared=", "y1 -= 1 if random.random() < 0.5: x1 += 1 else: x1 -=", "for a second agent\"\"\" y1= random.randint (0,99) #generates a number within the specified", "direction else: x0 -= 1 #decreases a step in the x direction \"\"\"", "theorem that gives an answer of 5 the randomised sequence gives varying answers\"\"\"", "step in the y coordinate if random.random() < 0.5:# generates a random number", "step in the x direction else: x0 -= 1 #decreases a step in", "possibility to create a range of numbers whereas random.random offers a range from", "random.randint (0,99) #same method as for previous agent if random.random() < 0.5: y1", "-= 1 if random.random() < 0.5: x1 += 1 else: x1 -= 1", "this case 0-99 x1= random.randint (0,99) #same method as for previous agent if", "random.random function, as the randint functions offers the possibility to create a range", "value of 0-0.99 y0 += 1 #increases a step in the y direction", "of 0-0.99 y0 += 1 #increases a step in the y direction else:", "direction else: y0 -= 1 #deccreases a step in the y direction #This", "number with a value of 0-0.99 y0 += 1 #increases a step in", "second agent\"\"\" y1= random.randint (0,99) #generates a number within the specified parameters in", "x coordinate if random.random() < 0.5: x0 += 1 #increases a step in", "to test pythagoras theorem that gives an answer of 5 the randomised sequence", "a second agent\"\"\" y1= random.randint (0,99) #generates a number within the specified parameters", "- x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5 being the square root", "if random.random() < 0.5:# generates a random number with a value of 0-0.99", "coordinate of agent in a 99*99 grid, this function varies from the random.random", "0 #y1 = 4 #x1 = 3 values used to test pythagoras theorem", "a number within the specified parameters in this case 0-99 x1= random.randint (0,99)", "a random number with a value of 0-0.99 y0 += 1 #increases a", "#increases a step in the y direction else: y0 -= 1 #deccreases a", "(0,99) #same method as for previous agent if random.random() < 0.5: y1 +=", "in the y direction else: y0 -= 1 #deccreases a step in the", "test pythagoras theorem that gives an answer of 5 the randomised sequence gives", "y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5 being", "x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5 being the square root of", "0-0.99 y0 += 1 #increases a step in the y direction else: y0", "0.5: x1 += 1 else: x1 -= 1 \"\"\" #y0 = 0 #x0", "squared, **0.5 being the square root of c, which is the distance between", "step in the x direction \"\"\" same action for a second agent\"\"\" y1=", "with a value of 0-0.99 y0 += 1 #increases a step in the", "1 else: x1 -= 1 \"\"\" #y0 = 0 #x0 = 0 #y1", "#decreases a step in the x direction \"\"\" same action for a second", "function, as the randint functions offers the possibility to create a range of", "if random.random() < 0.5: x0 += 1 #increases a step in the x", "+= 1 #increases a step in the y direction else: y0 -= 1", "same action for a second agent\"\"\" y1= random.randint (0,99) #generates a number within", "gives varying answers\"\"\" answer = (((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a", "specified parameters in this case 0-99 x1= random.randint (0,99) #same method as for", "the random.random function, as the randint functions offers the possibility to create a", "step in the y direction #This is the same movement for the x", "- y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+ b squared= c squared, **0.5", "offers a range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99) #Make Random", "an answer of 5 the randomised sequence gives varying answers\"\"\" answer = (((y0", "direction \"\"\" same action for a second agent\"\"\" y1= random.randint (0,99) #generates a", "the x direction else: x0 -= 1 #decreases a step in the x", "the y direction #This is the same movement for the x coordinate if", "99*99 grid, this function varies from the random.random function, as the randint functions", "whereas random.random offers a range from 0-1\"\"\" y0= random.randint (0,99) x0= random.randint (0,99)", "squared= c squared, **0.5 being the square root of c, which is the", "step in the y direction else: y0 -= 1 #deccreases a step in", "y direction #This is the same movement for the x coordinate if random.random()", "parameters in this case 0-99 x1= random.randint (0,99) #same method as for previous", "+= 1 else: y1 -= 1 if random.random() < 0.5: x1 += 1", "method as for previous agent if random.random() < 0.5: y1 += 1 else:", "-= 1 #deccreases a step in the y direction #This is the same", "of 5 the randomised sequence gives varying answers\"\"\" answer = (((y0 - y1)**2)", "y coordinate if random.random() < 0.5:# generates a random number with a value", "< 0.5: y1 += 1 else: y1 -= 1 if random.random() < 0.5:", "random.randint (0,99) x0= random.randint (0,99) #Make Random movement by 1 step in the", "by 1 step in the y coordinate if random.random() < 0.5:# generates a", "imports the random function \"\"\" ransomised position of y coordinate of agent in", "in the x direction else: x0 -= 1 #decreases a step in the", "pythagoras theorem that gives an answer of 5 the randomised sequence gives varying", "varying answers\"\"\" answer = (((y0 - y1)**2) + ((x0 - x1)**2))**0.5 \"\"\"a suared+", "distance between 1 and 2\"\"\" print (answer)# prints the result from the triangulation", "1 #increases a step in the x direction else: x0 -= 1 #decreases", "x0 += 1 #increases a step in the x direction else: x0 -=", "1 #deccreases a step in the y direction #This is the same movement", "in the x direction \"\"\" same action for a second agent\"\"\" y1= random.randint", "range of numbers whereas random.random offers a range from 0-1\"\"\" y0= random.randint (0,99)" ]
[ "VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES EM OUTRAS", "E MOSTRE AS 3 NO FINAL.''' numeros = list() pares = list() impares", "for indice, valor in enumerate(numeros): if valor % 2 == 0: pares.append(valor) elif", "3 NO FINAL.''' numeros = list() pares = list() impares = list() while", "E PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO FINAL.''' numeros", "enumerate(numeros): if valor % 2 == 0: pares.append(valor) elif valor % 2 ==", "LISTAS E MOSTRE AS 3 NO FINAL.''' numeros = list() pares = list()", "ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS", "list() impares = list() while True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer", "= list() while True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar? [S/N]:", "DIVIDA OS VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS", "resposta in 'Nn': break for indice, valor in enumerate(numeros): if valor % 2", "OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO FINAL.''' numeros = list() pares", "'))) resposta = str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn': break for", "valor % 2 == 0: pares.append(valor) elif valor % 2 == 1: impares.append(valor)", "valor: '))) resposta = str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn': break", "MOSTRE AS 3 NO FINAL.''' numeros = list() pares = list() impares =", "in 'Nn': break for indice, valor in enumerate(numeros): if valor % 2 ==", "print(f'A LISTA completa é: {numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A LISTA", "LISTA, DIVIDINDO VALORES ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA", "- LISTA, DIVIDINDO VALORES ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE", "if resposta in 'Nn': break for indice, valor in enumerate(numeros): if valor %", "impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A", "{numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A LISTA de ÍMPARES é: {impares}')", "é: {numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A LISTA de ÍMPARES é:", "break for indice, valor in enumerate(numeros): if valor % 2 == 0: pares.append(valor)", "pares.append(valor) elif valor % 2 == 1: impares.append(valor) print(f'A LISTA completa é: {numeros}')", "'''082 - LISTA, DIVIDINDO VALORES ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E", "')) if resposta in 'Nn': break for indice, valor in enumerate(numeros): if valor", "True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar? [S/N]: ')) if resposta", "elif valor % 2 == 1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A", "pares = list() impares = list() while True: numeros.append(int(input('Digite um valor: '))) resposta", "GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS", "resposta = str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn': break for indice,", "== 1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA de PARES é:", "= str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn': break for indice, valor", "DUAAS LISTAS E MOSTRE AS 3 NO FINAL.''' numeros = list() pares =", "'Nn': break for indice, valor in enumerate(numeros): if valor % 2 == 0:", "DIVIDINDO VALORES ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA.", "completa é: {numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A LISTA de ÍMPARES", "numeros = list() pares = list() impares = list() while True: numeros.append(int(input('Digite um", "0: pares.append(valor) elif valor % 2 == 1: impares.append(valor) print(f'A LISTA completa é:", "continuar? [S/N]: ')) if resposta in 'Nn': break for indice, valor in enumerate(numeros):", "LISTA completa é: {numeros}') print(f'A LISTA de PARES é: {pares}') print(f'A LISTA de", "PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES", "% 2 == 0: pares.append(valor) elif valor % 2 == 1: impares.append(valor) print(f'A", "LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES", "if valor % 2 == 0: pares.append(valor) elif valor % 2 == 1:", "in enumerate(numeros): if valor % 2 == 0: pares.append(valor) elif valor % 2", "VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO", "[S/N]: ')) if resposta in 'Nn': break for indice, valor in enumerate(numeros): if", "== 0: pares.append(valor) elif valor % 2 == 1: impares.append(valor) print(f'A LISTA completa", "impares = list() while True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar?", "QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E", "NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS E", "numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar? [S/N]: ')) if resposta in", "% 2 == 1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA de", "str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn': break for indice, valor in", "valor % 2 == 1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA", "VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES EM", "EM OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO FINAL.''' numeros = list()", "PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO FINAL.''' numeros =", "OS VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS 3", "= list() pares = list() impares = list() while True: numeros.append(int(input('Digite um valor:", "AS 3 NO FINAL.''' numeros = list() pares = list() impares = list()", "IMPARES E PARES EM OUTRAS DUAAS LISTAS E MOSTRE AS 3 NO FINAL.'''", "valor in enumerate(numeros): if valor % 2 == 0: pares.append(valor) elif valor %", "NO FINAL.''' numeros = list() pares = list() impares = list() while True:", "VALORES ENTRE LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA", "while True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar? [S/N]: ')) if", "= list() impares = list() while True: numeros.append(int(input('Digite um valor: '))) resposta =", "2 == 0: pares.append(valor) elif valor % 2 == 1: impares.append(valor) print(f'A LISTA", "2 == 1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA de PARES", "um valor: '))) resposta = str(input('Quer continuar? [S/N]: ')) if resposta in 'Nn':", "FINAL.''' numeros = list() pares = list() impares = list() while True: numeros.append(int(input('Digite", "indice, valor in enumerate(numeros): if valor % 2 == 0: pares.append(valor) elif valor", "list() pares = list() impares = list() while True: numeros.append(int(input('Digite um valor: ')))", "LISTAS. PROGRAMA QUE LEIA VÁRIOS VALORES E GUARDE NUMA LISTA. DIVIDA OS VALORES", "LISTA. DIVIDA OS VALORES IMPARES E PARES EM OUTRAS DUAAS LISTAS E MOSTRE", "list() while True: numeros.append(int(input('Digite um valor: '))) resposta = str(input('Quer continuar? [S/N]: '))", "1: impares.append(valor) print(f'A LISTA completa é: {numeros}') print(f'A LISTA de PARES é: {pares}')", "E GUARDE NUMA LISTA. DIVIDA OS VALORES IMPARES E PARES EM OUTRAS DUAAS" ]
[ "setFpgm(self, block): self.fpgm = block def setPrep(self, block): self.prep = block def addGlyph(self,", "def addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self, name, value): if name", "HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise", "name): try: return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name): return name", "if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not in self.__storageLookup: index =", "HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size,", "name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep", "{} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit))", "block def setPrep(self, block): self.prep = block def addGlyph(self, name, block): self.glyphs[name] =", "HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if", "Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit,", "self.__voidFunctionList.append(name) def addStorage(self, name): if name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name]", "name, value): self.__flagLookup[name] = value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError:", "value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\"", "= block def addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self, name, value):", "self.gasp = [] \"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\"", "def setFpgm(self, block): self.fpgm = block def setPrep(self, block): self.prep = block def", "HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self,", "__init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing, bool", "symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value", "None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {}", "size, bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string", "[] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {}", "def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError: raise HumbleError(\"Undeclared flag alias: {}\".format(name))", "name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self,", "doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self,", "index def addFunction(self, index, name, recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate", "{}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name]", "self.maxp = {} \"\"\"{string name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm", "= {} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing,", "symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self, block): self.fpgm", "index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name] = value", "len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self,", "def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name))", "self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier:", "value def setFpgm(self, block): self.fpgm = block def setPrep(self, block): self.prep = block", "block): self.fpgm = block def setPrep(self, block): self.prep = block def addGlyph(self, name,", "self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if", "= recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not in self.__storageLookup:", "KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except", "self.__flagLookup[name] = value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared", "self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index", "doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value):", "__future__ import absolute_import from .error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def", "= {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {}", "isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not in self.__storageLookup: index = len(self.__storageLookup)", "{}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name, recipe,", "HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {}", "identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name))", "{} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup", "self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name", "addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self, block): self.fpgm = block def", "{}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier:", "getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def", "try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name):", "return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try:", "block def addCvt(self, name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier:", "self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return", "index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] = index", "def addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self, block): self.fpgm = block", "{}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError: raise HumbleError(\"Undeclared flag alias:", "{} \"\"\"{string name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None", "def setPrep(self, block): self.prep = block def addGlyph(self, name, block): self.glyphs[name] = block", "CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index,", "recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not in self.__storageLookup: index", "except KeyError: return () def isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self,", "return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name): return name in self.__voidFunctionList", "= {} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup =", "index, name, recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name))", "function index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid:", "value): self.__flagLookup[name] = value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise", "setPrep(self, block): self.prep = block def addGlyph(self, name, block): self.glyphs[name] = block def", "name in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared", "def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name))", "bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int value}\"\"\" self.cvt = []", "= len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name] = value def", "self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self, name):", "identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function", "from .error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp =", "in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise HumbleError(\"Undeclared storage", "= None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name :", "= {} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup = {} def addGasp(self,", "symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\"", "name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self,", "bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int value}\"\"\" self.cvt", "data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit, bool doGray, bool", "except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name]", "{} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup = {}", "= len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name, recipe, isVoid): if", "index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not", "addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self,", "doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name :", "symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int value}\"\"\" self.cvt =", "try: return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name): return name in", "bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int", "block): self.prep = block def addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self,", "def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name))", "if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value)", "addStorage(self, name): if name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index", "value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt)", "= block def addCvt(self, name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT", "value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier:", "name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name):", "doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self, block):", "raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError:", "HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return", "index def addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self, name): try: return", "\"\"\"{string name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\"", "= index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name", "= index def addFunction(self, index, name, recipe, isVoid): if name in self.__functionLookup: raise", "identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return () def", "{} self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit,", "getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def", "block def addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self, name, value): if", "in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate", "raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError:", "parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit, bool doGray,", "except KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name]", "= [] \"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp", "name, block): self.glyphs[name] = block def addCvt(self, name, value): if name in self.__cvtLookup:", "= {} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup =", "[] \"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp =", "KeyError: return () def isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self, name):", "= None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup =", "= [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs =", "def addStorage(self, name): if name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] =", "name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name]", "getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name): return", "storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError: raise HumbleError(\"Undeclared", "int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None", "\"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string", "KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except", "def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def", "index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name)", ": Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList", "self.__storageLookup = {} self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit):", "if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] =", "self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return", "{} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup = {}", "= [] self.__storageLookup = {} self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray,", "addCvt(self, name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index", "def addFunction(self, index, name, recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function", "raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def", "if name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self,", "try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name):", "self.glyphs[name] = block def addCvt(self, name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate", "name): return name in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError:", "return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try:", "self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] =", "= value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT", "{} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def", "doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name]", "{}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self,", "\"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup", "self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value def", "name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise", "return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try:", "return () def isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self, name): try:", "KeyError: raise HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except", "len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name, recipe, isVoid): if name", "in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] =", "= index def addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self, name): try:", "doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name : int value}\"\"\"", "None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block", "\"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {}", "name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup = {}", "= {} self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size,", "raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name] = recipe", "def isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name]", "not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value):", "raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError:", "self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup", "self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return", "= {} \"\"\"{string name : int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm =", "identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError: raise HumbleError(\"Undeclared flag", "name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name,", "self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup = {} def addGasp(self, size, doGridFit,", "name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name)) index =", "function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index,", "name): try: return self.__cvtLookup[name] except KeyError: raise HumbleError(\"Undeclared CVT identifier: {}\".format(name)) def getFunctionIndex(self,", "block): self.glyphs[name] = block def addCvt(self, name, value): if name in self.__cvtLookup: raise", "function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return ()", "isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in", "() def isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self, name): try: return", "HumbleError(\"Undeclared storage identifier: {}\".format(name)) def getFlagValue(self, name): try: return self.__flagLookup[name] except KeyError: raise", "\"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup =", "self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function", "{} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup = {} def addGasp(self, size,", "import absolute_import from .error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self):", "addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self, name): try: return self.__cvtLookup[name] except", "except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name]", "from __future__ import absolute_import from .error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\"", "name): if name not in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def", "addFunction(self, index, name, recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier:", "self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup", "= value def setFpgm(self, block): self.fpgm = block def setPrep(self, block): self.prep =", "bool doGridfit, bool doGray, bool symSmoothing, bool symGridfit)]\"\"\" self.maxp = {} \"\"\"{string name", "recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index", "in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index: {} {}\".format(index, name)) self.__functionLookup[name] = index self.__functionRecipeLookup[name]", "self.__functionRecipeLookup[name] = recipe if isVoid: self.__voidFunctionList.append(name) def addStorage(self, name): if name not in", "symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name, value): self.maxp[name] =", "self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name): return name in self.__voidFunctionList def", "index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name, recipe, isVoid):", "try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def getFunctionRecipe(self, name):", "\"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs = {} \"\"\"{string name : Block block}\"\"\"", "getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared function identifier: {}\".format(name)) def", "self.maxp[name] = value def setFpgm(self, block): self.fpgm = block def setPrep(self, block): self.prep", "raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values(): raise HumbleError(\"Duplicate function index:", "self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup", "self.fpgm = block def setPrep(self, block): self.prep = block def addGlyph(self, name, block):", "= block def setPrep(self, block): self.prep = block def addGlyph(self, name, block): self.glyphs[name]", "[] self.__storageLookup = {} self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray, symSmoothing,", "self.__functionRecipeLookup = {} self.__voidFunctionList = [] self.__storageLookup = {} self.__flagLookup = {} def", "def addFlag(self, name, value): self.__flagLookup[name] = value def getCvtIndex(self, name): try: return self.__cvtLookup[name]", "in self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name]", "name, recipe, isVoid): if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if", "name, value): self.maxp[name] = value def setFpgm(self, block): self.fpgm = block def setPrep(self,", "absolute_import from .error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp", "self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name, recipe, isVoid): if name in", ".error import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = []", ": int value}\"\"\" self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep =", "identifier: {}\".format(name)) index = len(self.cvt) self.cvt.append(value) self.__cvtLookup[name] = index def addFunction(self, index, name,", "self.__storageLookup: index = len(self.__storageLookup) self.__storageLookup[name] = index def addFlag(self, name, value): self.__flagLookup[name] =", "symGridfit)) def addMaxp(self, name, value): self.maxp[name] = value def setFpgm(self, block): self.fpgm =", "CVT identifier: {}\".format(name)) def getFunctionIndex(self, name): try: return self.__functionLookup[name] except KeyError: raise HumbleError(\"Undeclared", "self.prep = block def addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self, name,", "value): self.maxp[name] = value def setFpgm(self, block): self.fpgm = block def setPrep(self, block):", "block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList = []", "Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup = {} self.__functionRecipeLookup = {} self.__voidFunctionList =", "def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self, name):", "return name in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except KeyError: raise", "self.glyphs = {} \"\"\"{string name : Block block}\"\"\" self.__cvtLookup = {} self.__functionLookup =", "self.__cvtLookup[name] = index def addFunction(self, index, name, recipe, isVoid): if name in self.__functionLookup:", "if name in self.__functionLookup: raise HumbleError(\"Duplicate function identifier: {}\".format(name)) if index in self.__functionLookup.values():", "isVoidFunction(self, name): return name in self.__voidFunctionList def getStorageIndex(self, name): try: return self.__storageLookup[name] except", "\"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit, bool", "def __init__(self): self.gasp = [] \"\"\"[(int size, bool doGridfit, bool doGray, bool symSmoothing,", "size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray, symSmoothing, symGridfit)) def addMaxp(self, name,", "def addCvt(self, name, value): if name in self.__cvtLookup: raise HumbleError(\"Duplicate CVT identifier: {}\".format(name))", "self.__flagLookup = {} def addGasp(self, size, doGridFit, doGray, symSmoothing, symGridfit): self.gasp.append((size, doGridFit, doGray,", "class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int size, bool", "{}\".format(name)) def getFunctionRecipe(self, name): try: return self.__functionRecipeLookup[name] except KeyError: return () def isVoidFunction(self,", "import HumbleError class Data(object): \"\"\"Manage parsed data\"\"\" def __init__(self): self.gasp = [] \"\"\"[(int", "self.cvt = [] \"\"\"[int]\"\"\" self.fpgm = None \"\"\"Block\"\"\" self.prep = None \"\"\"Block\"\"\" self.glyphs", "addGlyph(self, name, block): self.glyphs[name] = block def addCvt(self, name, value): if name in" ]
[ "= stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10]) print(\"The furthest stations are:", "(52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10]) print(\"The", "floodsystem.geo import stations_by_distance def run(): stations = build_station_list() p = (52.2053, 0.1218) distances", "p = (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations are: \",", "import stations_by_distance def run(): stations = build_station_list() p = (52.2053, 0.1218) distances =", "print(\"The closest stations are: \", distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if", "\", distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if __name__ == \"__main__\": print(\"***", "p) print(\"The closest stations are: \", distances[:10]) print(\"The furthest stations are: \", distances[-10:])", "<filename>Task1B.py from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance def run(): stations =", "are: \", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B: CUED Part IA", "from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance def run(): stations = build_station_list()", "== \"__main__\": print(\"*** Task 1B: CUED Part IA Flood Warning System ***\") run()", "stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10]) print(\"The furthest stations are: \",", "stations_by_distance def run(): stations = build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations,", "\", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B: CUED Part IA Flood", "are: \", distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if __name__ == \"__main__\":", "floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance def run(): stations = build_station_list() p", "distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B: CUED Part IA Flood Warning", "build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations are:", "0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10]) print(\"The furthest", "print(\"The furthest stations are: \", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B:", "stations are: \", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B: CUED Part", "stations = build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest", "def run(): stations = build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations, p)", "= build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations", "distances = stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10]) print(\"The furthest stations", "build_station_list from floodsystem.geo import stations_by_distance def run(): stations = build_station_list() p = (52.2053,", "import build_station_list from floodsystem.geo import stations_by_distance def run(): stations = build_station_list() p =", "run(): stations = build_station_list() p = (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The", "distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task", "furthest stations are: \", distances[-10:]) if __name__ == \"__main__\": print(\"*** Task 1B: CUED", "stations are: \", distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if __name__ ==", "__name__ == \"__main__\": print(\"*** Task 1B: CUED Part IA Flood Warning System ***\")", "if __name__ == \"__main__\": print(\"*** Task 1B: CUED Part IA Flood Warning System", "from floodsystem.geo import stations_by_distance def run(): stations = build_station_list() p = (52.2053, 0.1218)", "= (52.2053, 0.1218) distances = stations_by_distance(stations, p) print(\"The closest stations are: \", distances[:10])", "closest stations are: \", distances[:10]) print(\"The furthest stations are: \", distances[-10:]) if __name__" ]
[ "(2017b) Time series classification from scratch with deep neural networks: #A strong baseline.", "scratch with deep neural networks: #A strong baseline. In: International Joint Conference on", "<NAME>, <NAME> (2017b) Time series classification from scratch with deep neural networks: #A", "FCNNs #<NAME>, <NAME>, <NAME> (2017b) Time series classification from scratch with deep neural", "h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h = self.gap(h) h = self.lin(h)", "Neural Networks, pp 1578–1585 import torch.nn as nn import torch.optim as optim from", "self).__init__() #self.activation = nn.Softmax(dim=1) # This is include in the loss self.conv1 =", "= self.conv2(h) h = self.conv3(h) h = self.gap(h) h = self.lin(h) return h", "1578–1585 import torch.nn as nn import torch.optim as optim from . import Utility", "as optim from . import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs,", "<NAME> (2017b) Time series classification from scratch with deep neural networks: #A strong", "Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x):", "the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3", "pp 1578–1585 import torch.nn as nn import torch.optim as optim from . import", "out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h =", "Joint Conference on Neural Networks, pp 1578–1585 import torch.nn as nn import torch.optim", "5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature)", "h = self.conv2(h) h = self.conv3(h) h = self.gap(h) h = self.lin(h) return", "#A strong baseline. In: International Joint Conference on Neural Networks, pp 1578–1585 import", "Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin =", "# FCNNs #<NAME>, <NAME>, <NAME> (2017b) Time series classification from scratch with deep", "import torch.optim as optim from . import Utility class FCNNs(nn.Module): def __init__(self, in_feature,", "x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h = self.gap(h) h =", "series classification from scratch with deep neural networks: #A strong baseline. In: International", "import torch.nn as nn import torch.optim as optim from . import Utility class", "import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1)", "FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is", "Conference on Neural Networks, pp 1578–1585 import torch.nn as nn import torch.optim as", "#self.activation = nn.Softmax(dim=1) # This is include in the loss self.conv1 = Utility.ConvBlock(in_feature,", "= Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin", "Time series classification from scratch with deep neural networks: #A strong baseline. In:", "optim from . import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__()", "include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256,", "deep neural networks: #A strong baseline. In: International Joint Conference on Neural Networks,", "#<NAME>, <NAME>, <NAME> (2017b) Time series classification from scratch with deep neural networks:", "self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h) h =", "= Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128,", "self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP()", "with deep neural networks: #A strong baseline. In: International Joint Conference on Neural", "nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h", "= Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h)", "self.conv2(h) h = self.conv3(h) h = self.gap(h) h = self.lin(h) return h def", "<gh_stars>0 # FCNNs #<NAME>, <NAME>, <NAME> (2017b) Time series classification from scratch with", "networks: #A strong baseline. In: International Joint Conference on Neural Networks, pp 1578–1585", ". import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation =", "in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is include in the", "def forward(self, x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h = self.gap(h)", "forward(self, x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h) h = self.gap(h) h", "= self.gap(h) h = self.lin(h) return h def getOptimizer(self): return optim.Adam(self.parameters(), lr=0.001, betas=(0.9,0.999),eps=1e-7)", "Networks, pp 1578–1585 import torch.nn as nn import torch.optim as optim from .", "self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def", "128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap", "strong baseline. In: International Joint Conference on Neural Networks, pp 1578–1585 import torch.nn", "from scratch with deep neural networks: #A strong baseline. In: International Joint Conference", "class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This", "super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is include in the loss self.conv1", "h = self.conv3(h) h = self.gap(h) h = self.lin(h) return h def getOptimizer(self):", "= Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self,", "nn.Softmax(dim=1) # This is include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8)", "self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256,", "International Joint Conference on Neural Networks, pp 1578–1585 import torch.nn as nn import", "classification from scratch with deep neural networks: #A strong baseline. In: International Joint", "neural networks: #A strong baseline. In: International Joint Conference on Neural Networks, pp", "h = self.gap(h) h = self.lin(h) return h def getOptimizer(self): return optim.Adam(self.parameters(), lr=0.001,", "in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5)", "Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h) h", "= self.conv3(h) h = self.gap(h) h = self.lin(h) return h def getOptimizer(self): return", "__init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is include in", "is include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128,", "Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) #", "= nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h = self.conv2(h) h = self.conv3(h)", "on Neural Networks, pp 1578–1585 import torch.nn as nn import torch.optim as optim", "= nn.Softmax(dim=1) # This is include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128,", "8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap =", "def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is include", "This is include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 =", "In: International Joint Conference on Neural Networks, pp 1578–1585 import torch.nn as nn", "self.conv3(h) h = self.gap(h) h = self.lin(h) return h def getOptimizer(self): return optim.Adam(self.parameters(),", "Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3)", "torch.nn as nn import torch.optim as optim from . import Utility class FCNNs(nn.Module):", "128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x)", "3) self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h", "out_feature): super(FCNNs, self).__init__() #self.activation = nn.Softmax(dim=1) # This is include in the loss", "# This is include in the loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2", "as nn import torch.optim as optim from . import Utility class FCNNs(nn.Module): def", "self.gap = Utility.GAP() self.lin = nn.Linear(128, out_feature) def forward(self, x): h=self.conv1(x) h =", "256, 5) self.conv3 = Utility.ConvBlock(256, 128, 3) self.gap = Utility.GAP() self.lin = nn.Linear(128,", "loss self.conv1 = Utility.ConvBlock(in_feature, 128, 8) self.conv2 = Utility.ConvBlock(128, 256, 5) self.conv3 =", "baseline. In: International Joint Conference on Neural Networks, pp 1578–1585 import torch.nn as", "torch.optim as optim from . import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature):", "nn import torch.optim as optim from . import Utility class FCNNs(nn.Module): def __init__(self,", "from . import Utility class FCNNs(nn.Module): def __init__(self, in_feature, out_feature): super(FCNNs, self).__init__() #self.activation" ]
[ "= status self.name = name self.description = description self.entry = entry self.parameters =", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "self.artifactpath = artifactpath self.type = atype self.step = step self.artifactname = artifactname self.meta", "= parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime =", "runid self.source = source self.step = step self.fsname = fsname self.username = username", "License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "= strategy self.custom = custom self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object):", "fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp", "image self.jobId = jobid class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def", "governing permissions and limitations under the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8", "strategy self.custom = custom self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\"", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "class of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname,", "self.fsname = fsname self.username = username self.artifactpath = artifactpath self.type = atype self.step", "start_time, end_time, image, jobid): self.name = name self.deps = deps self.parameters = parameters", "2021 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0", "class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self, runId, fsname, username, status,", "self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source", "the License for the specific language governing permissions and limitations under the License.", "parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId =", "fsname, username, status, name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg,", "= source self.step = step self.fsname = fsname self.username = username self.expiredtime =", "License for the specific language governing permissions and limitations under the License. \"\"\"", "Unless required by applicable law or agreed to in writing, software distributed under", "RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid,", "artifactname, meta, createtime, updatetime): self.runid = runid self.fsname = fsname self.username = username", "self.source = source self.step = step self.fsname = fsname self.username = username self.expiredtime", "expiredtime self.strategy = strategy self.custom = custom self.createtime = createtime self.updatetime = updatetime", "name self.deps = deps self.parameters = parameters self.command = command self.env = env", "entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId", "= runMsg self.createTime = createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the class", "the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "runMsg self.createTime = createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the class of", "License, Version 2.0 (the \"License\"); you may not use this file except in", "dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname =", "info\"\"\" def __init__(self, name, deps, parameters, command, env, status, start_time, end_time, image, jobid):", "= updatetime class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def __init__(self, runid,", "updateTime self.source = source self.runMsg = runMsg self.createTime = createTime self.activateTime = activateTime", "coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self, runId, fsname,", "source, step, fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp", "self.name = name self.description = description self.entry = entry self.parameters = parameters self.run_yaml", "the class of job info\"\"\" def __init__(self, name, deps, parameters, command, env, status,", "(c) 2021 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version", "self.cacheid = cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid = runid self.source", "firstfp self.secondfp = secondfp self.runid = runid self.source = source self.step = step", "software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "by applicable law or agreed to in writing, software distributed under the License", "self.env = env self.status = status self.start_time = start_time self.end_time = end_time self.image", "self.custom = custom self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the", "firstfp, secondfp, runid, source, step, fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid", "atype self.step = step self.artifactname = artifactname self.meta = meta self.createtime = createtime", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License", "image, jobid): self.name = name self.deps = deps self.parameters = parameters self.command =", "= firstfp self.secondfp = secondfp self.runid = runid self.source = source self.step =", "of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname, username,", "the class of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source, step,", "activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname = fsname self.username = username self.status", "= parameters self.command = command self.env = env self.status = status self.start_time =", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "__init__(self, runid, fsname, username, artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid =", "in compliance with the License. You may obtain a copy of the License", "of job info\"\"\" def __init__(self, name, deps, parameters, command, env, status, start_time, end_time,", "status self.start_time = start_time self.end_time = end_time self.image = image self.jobId = jobid", "KIND, either express or implied. See the License for the specific language governing", "in writing, software distributed under the License is distributed on an \"AS IS\"", "writing, software distributed under the License is distributed on an \"AS IS\" BASIS,", "= status self.start_time = start_time self.end_time = end_time self.image = image self.jobId =", "\"\"\" Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache", "run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source = source", "end_time self.image = image self.jobId = jobid class RunCacheInfo(object): \"\"\" the class of", "or agreed to in writing, software distributed under the License is distributed on", "= runId self.fsname = fsname self.username = username self.status = status self.name =", "self.deps = deps self.parameters = parameters self.command = command self.env = env self.status", "deps self.parameters = parameters self.command = command self.env = env self.status = status", "cacheid, firstfp, secondfp, runid, source, step, fsname, username, expiredtime, strategy, custom, createtime, updatetime):", "env, status, start_time, end_time, image, jobid): self.name = name self.deps = deps self.parameters", "status, name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime):", "# -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self,", "runid self.fsname = fsname self.username = username self.artifactpath = artifactpath self.type = atype", "self.secondfp = secondfp self.runid = runid self.source = source self.step = step self.fsname", "description self.entry = entry self.parameters = parameters self.run_yaml = run_yaml self.runtime = runtime", "self.status = status self.start_time = start_time self.end_time = end_time self.image = image self.jobId", "parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime = updateTime", "= secondfp self.runid = runid self.source = source self.step = step self.fsname =", "OR CONDITIONS OF ANY KIND, either express or implied. See the License for", "source self.step = step self.fsname = fsname self.username = username self.expiredtime = expiredtime", "OF ANY KIND, either express or implied. See the License for the specific", "JobInfo(object): \"\"\" the class of job info\"\"\" def __init__(self, name, deps, parameters, command,", "custom, createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid", "source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname = fsname self.username", "self.end_time = end_time self.image = image self.jobId = jobid class RunCacheInfo(object): \"\"\" the", "dockerEnv self.updateTime = updateTime self.source = source self.runMsg = runMsg self.createTime = createTime", "the specific language governing permissions and limitations under the License. \"\"\" #!/usr/bin/env python3", "self.step = step self.artifactname = artifactname self.meta = meta self.createtime = createtime self.updatetime", "may not use this file except in compliance with the License. You may", "self.runMsg = runMsg self.createTime = createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "= image self.jobId = jobid class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\"", "artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype, step, artifactname, meta, createtime,", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname = fsname self.username = username", "self.firstfp = firstfp self.secondfp = secondfp self.runid = runid self.source = source self.step", "\"\"\" the class of job info\"\"\" def __init__(self, name, deps, parameters, command, env,", "username, artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid = runid self.fsname =", "parameters self.command = command self.env = env self.status = status self.start_time = start_time", "= start_time self.end_time = end_time self.image = image self.jobId = jobid class RunCacheInfo(object):", "__init__(self, runId, fsname, username, status, name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime,", "runid, fsname, username, artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid = runid", "= username self.status = status self.name = name self.description = description self.entry =", "createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid =", "jobid class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def __init__(self, cacheid, firstfp,", "runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname = fsname self.username =", "limitations under the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object):", "runId, fsname, username, status, name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source,", "See the License for the specific language governing permissions and limitations under the", "-*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self, runId, fsname, username,", "self.step = step self.fsname = fsname self.username = username self.expiredtime = expiredtime self.strategy", "strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp = secondfp", "runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source = source self.runMsg = runMsg", "this file except in compliance with the License. You may obtain a copy", "name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init", "self.expiredtime = expiredtime self.strategy = strategy self.custom = custom self.createtime = createtime self.updatetime", "jobid): self.name = name self.deps = deps self.parameters = parameters self.command = command", "self.fsname = fsname self.username = username self.expiredtime = expiredtime self.strategy = strategy self.custom", "meta, createtime, updatetime): self.runid = runid self.fsname = fsname self.username = username self.artifactpath", "\"License\"); you may not use this file except in compliance with the License.", "\"\"\" self.runId = runId self.fsname = fsname self.username = username self.status = status", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "you may not use this file except in compliance with the License. You", "PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software distributed under the License is distributed on an", "__init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname, username, expiredtime, strategy, custom, createtime,", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "custom self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class of", "self.strategy = strategy self.custom = custom self.createtime = createtime self.updatetime = updatetime class", "implied. See the License for the specific language governing permissions and limitations under", "= custom self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class", "Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the \"License\");", "createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the class of job info\"\"\" def", "\"\"\" the class of artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype,", "username self.status = status self.name = name self.description = description self.entry = entry", "username, status, name, description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime,", "= entry self.parameters = parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv =", "updatetime): self.runid = runid self.fsname = fsname self.username = username self.artifactpath = artifactpath", "Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License,", "expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp =", "= step self.artifactname = artifactname self.meta = meta self.createtime = createtime self.updatetime =", "use this file except in compliance with the License. You may obtain a", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "self.image = image self.jobId = jobid class RunCacheInfo(object): \"\"\" the class of runcache", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use", "createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def", "self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def __init__(self,", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "info\"\"\" def __init__(self, runId, fsname, username, status, name, description, entry, parameters, run_yaml, runtime,", "required by applicable law or agreed to in writing, software distributed under the", "artifactpath self.type = atype self.step = step self.artifactname = artifactname self.meta = meta", "self.dockerEnv = dockerEnv self.updateTime = updateTime self.source = source self.runMsg = runMsg self.createTime", "env self.status = status self.start_time = start_time self.end_time = end_time self.image = image", "__init__(self, name, deps, parameters, command, env, status, start_time, end_time, image, jobid): self.name =", "deps, parameters, command, env, status, start_time, end_time, image, jobid): self.name = name self.deps", "= expiredtime self.strategy = strategy self.custom = custom self.createtime = createtime self.updatetime =", "= end_time self.image = image self.jobId = jobid class RunCacheInfo(object): \"\"\" the class", "= activateTime class JobInfo(object): \"\"\" the class of job info\"\"\" def __init__(self, name,", "self.activateTime = activateTime class JobInfo(object): \"\"\" the class of job info\"\"\" def __init__(self,", "self.updateTime = updateTime self.source = source self.runMsg = runMsg self.createTime = createTime self.activateTime", "= name self.description = description self.entry = entry self.parameters = parameters self.run_yaml =", "atype, step, artifactname, meta, createtime, updatetime): self.runid = runid self.fsname = fsname self.username", "the class of artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype, step,", "self.jobId = jobid class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def __init__(self,", "self.runId = runId self.fsname = fsname self.username = username self.status = status self.name", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Reserve. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not", "language governing permissions and limitations under the License. \"\"\" #!/usr/bin/env python3 # -*-", "command, env, status, start_time, end_time, image, jobid): self.name = name self.deps = deps", "not use this file except in compliance with the License. You may obtain", "= fsname self.username = username self.expiredtime = expiredtime self.strategy = strategy self.custom =", "= cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid = runid self.source =", "under the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the", "description, entry, parameters, run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\"", "step self.artifactname = artifactname self.meta = meta self.createtime = createtime self.updatetime = updatetime", "def __init__(self, runid, fsname, username, artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid", "= env self.status = status self.start_time = start_time self.end_time = end_time self.image =", "= source self.runMsg = runMsg self.createTime = createTime self.activateTime = activateTime class JobInfo(object):", "ANY KIND, either express or implied. See the License for the specific language", "= dockerEnv self.updateTime = updateTime self.source = source self.runMsg = runMsg self.createTime =", "class of artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype, step, artifactname,", "file except in compliance with the License. You may obtain a copy of", "status self.name = name self.description = description self.entry = entry self.parameters = parameters", "2.0 (the \"License\"); you may not use this file except in compliance with", "self.type = atype self.step = step self.artifactname = artifactname self.meta = meta self.createtime", "python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "username self.artifactpath = artifactpath self.type = atype self.step = step self.artifactname = artifactname", "self.createTime = createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the class of job", "the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", "self.source = source self.runMsg = runMsg self.createTime = createTime self.activateTime = activateTime class", "step, artifactname, meta, createtime, updatetime): self.runid = runid self.fsname = fsname self.username =", "(the \"License\"); you may not use this file except in compliance with the", "the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class", "\"\"\" the class of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source,", "= runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source = source self.runMsg =", "activateTime class JobInfo(object): \"\"\" the class of job info\"\"\" def __init__(self, name, deps,", "class of job info\"\"\" def __init__(self, name, deps, parameters, command, env, status, start_time,", "fsname, username, artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid = runid self.fsname", "= username self.expiredtime = expiredtime self.strategy = strategy self.custom = custom self.createtime =", "self.username = username self.status = status self.name = name self.description = description self.entry", "ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath,", "Rights Reserve. Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed", "All Rights Reserve. Licensed under the Apache License, Version 2.0 (the \"License\"); you", "self.createtime = createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class of artiface", "artifactpath, atype, step, artifactname, meta, createtime, updatetime): self.runid = runid self.fsname = fsname", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "= artifactpath self.type = atype self.step = step self.artifactname = artifactname self.meta =", "cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid = runid self.source = source", "step self.fsname = fsname self.username = username self.expiredtime = expiredtime self.strategy = strategy", "law or agreed to in writing, software distributed under the License is distributed", "self.description = description self.entry = entry self.parameters = parameters self.run_yaml = run_yaml self.runtime", "Version 2.0 (the \"License\"); you may not use this file except in compliance", "the Apache License, Version 2.0 (the \"License\"); you may not use this file", "self.parameters = parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime", "fsname self.username = username self.artifactpath = artifactpath self.type = atype self.step = step", "RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self, runId, fsname, username, status, name,", "createtime, updatetime): self.runid = runid self.fsname = fsname self.username = username self.artifactpath =", "under the Apache License, Version 2.0 (the \"License\"); you may not use this", "class of RunInfo info\"\"\" def __init__(self, runId, fsname, username, status, name, description, entry,", "either express or implied. See the License for the specific language governing permissions", "\"\"\"the class of RunInfo info\"\"\" def __init__(self, runId, fsname, username, status, name, description,", "= fsname self.username = username self.status = status self.name = name self.description =", "run_yaml, runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId", "= updateTime self.source = source self.runMsg = runMsg self.createTime = createTime self.activateTime =", "class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def __init__(self, runid, fsname, username,", "Apache License, Version 2.0 (the \"License\"); you may not use this file except", "or implied. See the License for the specific language governing permissions and limitations", "fsname self.username = username self.expiredtime = expiredtime self.strategy = strategy self.custom = custom", "= createtime self.updatetime = updatetime class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\"", "updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp = secondfp self.runid = runid", "CONDITIONS OF ANY KIND, either express or implied. See the License for the", "and limitations under the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class", "permissions and limitations under the License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*-", "to in writing, software distributed under the License is distributed on an \"AS", "= name self.deps = deps self.parameters = parameters self.command = command self.env =", "secondfp self.runid = runid self.source = source self.step = step self.fsname = fsname", "= runid self.source = source self.step = step self.fsname = fsname self.username =", "= step self.fsname = fsname self.username = username self.expiredtime = expiredtime self.strategy =", "= jobid class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def __init__(self, cacheid,", "except in compliance with the License. You may obtain a copy of the", "License. \"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of", "fsname self.username = username self.status = status self.name = name self.description = description", "self.command = command self.env = env self.status = status self.start_time = start_time self.end_time", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype, step, artifactname, meta, createtime, updatetime):", "RunInfo info\"\"\" def __init__(self, runId, fsname, username, status, name, description, entry, parameters, run_yaml,", "self.start_time = start_time self.end_time = end_time self.image = image self.jobId = jobid class", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "= runid self.fsname = fsname self.username = username self.artifactpath = artifactpath self.type =", "self.runid = runid self.source = source self.step = step self.fsname = fsname self.username", "runid, source, step, fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid", "of RunInfo info\"\"\" def __init__(self, runId, fsname, username, status, name, description, entry, parameters,", "self.entry = entry self.parameters = parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv", "\"\"\" #!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo", "\"\"\"init \"\"\" self.runId = runId self.fsname = fsname self.username = username self.status =", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,", "= description self.entry = entry self.parameters = parameters self.run_yaml = run_yaml self.runtime =", "start_time self.end_time = end_time self.image = image self.jobId = jobid class RunCacheInfo(object): \"\"\"", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.status = status self.name = name self.description = description self.entry = entry self.parameters", "def __init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname, username, expiredtime, strategy, custom,", "name, deps, parameters, command, env, status, start_time, end_time, image, jobid): self.name = name", "class JobInfo(object): \"\"\" the class of job info\"\"\" def __init__(self, name, deps, parameters,", "username self.expiredtime = expiredtime self.strategy = strategy self.custom = custom self.createtime = createtime", "self.username = username self.expiredtime = expiredtime self.strategy = strategy self.custom = custom self.createtime", "def __init__(self, name, deps, parameters, command, env, status, start_time, end_time, image, jobid): self.name", "compliance with the License. You may obtain a copy of the License at", "command self.env = env self.status = status self.start_time = start_time self.end_time = end_time", "parameters, command, env, status, start_time, end_time, image, jobid): self.name = name self.deps =", "runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname, username, expiredtime,", "express or implied. See the License for the specific language governing permissions and", "#!/usr/bin/env python3 # -*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\"", "self.fsname = fsname self.username = username self.status = status self.name = name self.description", "updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname = fsname", "= createTime self.activateTime = activateTime class JobInfo(object): \"\"\" the class of job info\"\"\"", "job info\"\"\" def __init__(self, name, deps, parameters, command, env, status, start_time, end_time, image,", "= run_yaml self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source =", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "= username self.artifactpath = artifactpath self.type = atype self.step = step self.artifactname =", "for the specific language governing permissions and limitations under the License. \"\"\" #!/usr/bin/env", "end_time, image, jobid): self.name = name self.deps = deps self.parameters = parameters self.command", "applicable law or agreed to in writing, software distributed under the License is", "step, fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp =", "= command self.env = env self.status = status self.start_time = start_time self.end_time =", "def __init__(self, runId, fsname, username, status, name, description, entry, parameters, run_yaml, runtime, dockerEnv,", "source self.runMsg = runMsg self.createTime = createTime self.activateTime = activateTime class JobInfo(object): \"\"\"", "name self.description = description self.entry = entry self.parameters = parameters self.run_yaml = run_yaml", "status, start_time, end_time, image, jobid): self.name = name self.deps = deps self.parameters =", "info\"\"\" def __init__(self, cacheid, firstfp, secondfp, runid, source, step, fsname, username, expiredtime, strategy,", "-*- coding:utf8 -*- class RunInfo(object): \"\"\"the class of RunInfo info\"\"\" def __init__(self, runId,", "runtime, dockerEnv, updateTime, source, runMsg, createTime, activateTime): \"\"\"init \"\"\" self.runId = runId self.fsname", "= deps self.parameters = parameters self.command = command self.env = env self.status =", "class RunCacheInfo(object): \"\"\" the class of runcache info\"\"\" def __init__(self, cacheid, firstfp, secondfp,", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "self.runid = runid self.fsname = fsname self.username = username self.artifactpath = artifactpath self.type", "updatetime class ArtifaceInfo(object): \"\"\" the class of artiface info\"\"\" def __init__(self, runid, fsname,", "self.runtime = runtime self.dockerEnv = dockerEnv self.updateTime = updateTime self.source = source self.runMsg", "self.name = name self.deps = deps self.parameters = parameters self.command = command self.env", "specific language governing permissions and limitations under the License. \"\"\" #!/usr/bin/env python3 #", "self.parameters = parameters self.command = command self.env = env self.status = status self.start_time", "runId self.fsname = fsname self.username = username self.status = status self.name = name", "= fsname self.username = username self.artifactpath = artifactpath self.type = atype self.step =", "secondfp, runid, source, step, fsname, username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid =", "of artiface info\"\"\" def __init__(self, runid, fsname, username, artifactpath, atype, step, artifactname, meta,", "entry self.parameters = parameters self.run_yaml = run_yaml self.runtime = runtime self.dockerEnv = dockerEnv", "= atype self.step = step self.artifactname = artifactname self.meta = meta self.createtime =", "username, expiredtime, strategy, custom, createtime, updatetime): self.cacheid = cacheid self.firstfp = firstfp self.secondfp", "with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software", "self.username = username self.artifactpath = artifactpath self.type = atype self.step = step self.artifactname" ]
[ "= definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String):", "# @RMF TODO: @Incomplete if the one of prevents extra members that are", "GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition else if (validation_type == RootTypes.Object):", "RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes:", "is a definition, values should probably happen in a different loaded_ place if", "type_definition = type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else if ('extends' in", "GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) != length_value): return False else if", "definition: if data > definition['max']: return False if 'regex' in definition: if not", "pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes():", "RootTypes.String): for element in data: if not Validate(context, element, elements_type): return False else", "(type_name != None): if (type_name in BasicTypes): return type_name if (type_name in checked_types):", "definition['length']): return False if 'elements' in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value)", "= { 'type', 'min', 'max', 'regex', 'extends', # rmf todo: this is important,", "True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value = definition['length'] length_type", "value, definition): self.data_type = data_type self.value = value self.definition = definition def ValitateTypeMatch(context,", "if not found: return False return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length'", "def __init__(self, data_type, value, definition): self.data_type = data_type self.value = value self.definition =", "definition) else: # rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success) return", "str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete", "(GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None):", "data < definition['min']: return False if 'max' in definition: if data > definition['max']:", "GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in data: if not Validate(context, element,", "RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any", "members that are defined outside of one_of then this validation might fail when", "'members', 'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType = { RootTypes.Bool :", "type_name return None def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value", "of prevents extra members that are defined outside of one_of then this validation", "type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if ('extends' in type_defintion)", "False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return", "return None # prevent circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return", "Any = 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends', # rmf", "in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array): success", "def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name])", "in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition,", "(dict), RootTypes.Any : () } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String }", "type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use definition['type'], it should be based", "in BasicTypes): return type_name if (type_name in checked_types): return None # prevent circular", "= True break if not found: return False return True def ValidateDefinitionOfArrayType(context, data,", "but whether it is a definition, values should probably happen in a different", "!= None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected", "'delete_members' # from parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int :", "it's a dict, but whether it is a definition, values should probably happen", "} BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool", "if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's not just about whether it's", "return False if 'min' in definition: if data < definition['min']: return False if", "def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name ==", "from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified", "type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition", "return False if not ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in definition:", "else: # rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success) return False", "== RootTypes.Int): if (len(data) != length_value): return False else if (length_type == RootTypes.Object):", "if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if not found: return False", "return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete allow", "RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float,", "(basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes =", "in definition: if not re.match(definition['regex']): return False if 'one_of' in definition: found =", "type name \" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in", "just about whether it's a dict, but whether it is a definition, values", "\" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf", ": GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString } class DefinitionNode(): def __init__(self,", "None): LogError(\"Expected value \" + string_buffer + \" to be of type \"", "LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool", "= GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False else if (validation_type ==", ": () } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers =", "type_name) else: LogValidationCheck(data, type_name, success) return False else if (validation_type == RootTypes.Object): definition", "RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete validate objects", "RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified =", "== RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this doesn't", "extending multiple types if not definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context,", "len(data), definition['length']): return False if 'elements' in definition: elements_value = definition['elements'] elements_type =", "data_type self.value = value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type =", "DefinitionNode(): def __init__(self, definition): self.definition = definition class DataNode(): def __init__(self, data_type, value,", "LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else:", "None def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer)", "False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete allow extending", "allow extending multiple types if not definition['extends'] in context.loaded_definitions: return False if not", "outside of one_of then this validation might fail when it should actually be", "should be based on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String):", "support extending either array or string, I think. if (root_type in BasicTypes): success", "data, definition) else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else:", "else: LogValidationCheck(data, type_name, success) return False else if (validation_type == RootTypes.Object): definition =", "one of prevents extra members that are defined outside of one_of then this", "ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int = 'Int' Float", "'min', 'max', 'regex', 'extends', # rmf todo: this is important, but requires partial", "definition) else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: #", "= GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition else if (validation_type ==", "ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if 'min' in definition: if data", "definition: #rmf todo: @incomplete allow extending multiple types if not definition['extends'] in context.loaded_definitions:", "= ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data,", "for element in data: if not Validate(context, element, elements_type): return False else if", "data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return", "elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in", "in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else if", "make this able to be nested 'members', 'name', 'required', 'delete_members' # from parent", "use definition['type'], it should be based on explicit extension validation_type = GetBasicType(type_name_or_definition) if", "in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type']", "or string, I think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition)", "False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name", "'extends' in definition: #rmf todo: @incomplete allow extending multiple types if not definition['extends']", "to validate against type that is data value\") LogValidationCheck(data, type_name, success) return False", "ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name,", "explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition else", "extra members that are defined outside of one_of then this validation might fail", "type_name) LogValidationCheck(data, type_name, success) return success else if (type_name in context.loaded_definitions): #rmf todo:", "GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int =", "RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \"", "a dict, but whether it is a definition, values should probably happen in", "references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if", ": GetFloat, RootTypes.String : GetString } class DefinitionNode(): def __init__(self, definition): self.definition =", "GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString } class DefinitionNode(): def __init__(self, definition):", "(type_name not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion):", "if (type_name == RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for", "not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if 'min' in definition: if", "def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name =", "while (type_name != None): if (type_name in BasicTypes): return type_name if (type_name in", "partial validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete will need more work", "if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data): return (GetBasicType(data) != None)", "else if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf", "None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if ('extends' in", "'type', 'min', 'max', 'regex', 'extends', # rmf todo: this is important, but requires", "type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while (type_name != None): if (type_name", "GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False else if (validation_type == RootTypes.Object):", "if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return False", "in context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']): return False if 'type'", "type that is data value\") LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name]", "whether it's a dict, but whether it is a definition, values should probably", "be of type \" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context,", "dict): definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if", "+ string_buffer + \" to be of type \" + type_name) parsed_value =", "('type' in type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends'] return", "work to make this able to be nested 'members', 'name', 'required', 'delete_members' #", "in context.loaded_definitions): #rmf todo: @incomplete it's not just about whether it's a dict,", "} RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float : (float),", "name \" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition:", "if (elements_type == RootTypes.String): for element in data: if not Validate(context, element, elements_type):", "then this validation might fail when it should actually be valid if ValidateDefinitionOfBasicType(context,", "it's not just about whether it's a dict, but whether it is a", "if not re.match(definition['regex']): return False if 'one_of' in definition: found = False for", "= 'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers = { 'type', 'min',", "prevents extra members that are defined outside of one_of then this validation might", "type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while (type_name !=", "break if not found: return False return True def ValidateDefinitionOfArrayType(context, data, definition): if", "if (validation_type == RootTypes.String): type_name = type_name_or_definition else if (validation_type == RootTypes.Object): type_definition", "in type_defintion): return type_definition['type'] else if ('extends' in type_defition): type_name = type_defintion['extends'] else:", "return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if", "prevent circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None type_defintion =", "definition: length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data)", "probably happen in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to", "= type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while (type_name != None): if", "False else: return False if 'min' in definition: if data < definition['min']: return", "'one_of', # rmf todo: @incomplete will need more work to make this able", "GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use definition['type'], it should be", "if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False", "+ \" to be of type \" + type_name) parsed_value = ParseValue(string_buffer) return", "pass LogValidationCheck(data, type_name, success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition)", "LogValidationCheck(data, type_name, success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def", "type_name, success) return success else if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's", "for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data):", "on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition", "(root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array):", "return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use definition['type'],", "= False for potential_node in definition['one_of']: # @RMF TODO: @Incomplete if the one", "RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in definition: elements_value", "rmf todo: this is important, but requires partial validation 'default_value', 'length', 'one_of', #", "RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float", "if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success", "'min' in definition: if data < definition['min']: return False if 'max' in definition:", "of type \" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion):", "type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while (type_name != None):", "parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \" + string_buffer +", "able to be nested 'members', 'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType", "BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data): return (GetBasicType(data) !=", "rmf todo: @incomplete will need more work to make this able to be", "'length', 'one_of', # rmf todo: @incomplete will need more work to make this", "return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value ==", "(validation_type == RootTypes.String): type_name = type_name_or_definition else if (validation_type == RootTypes.Object): type_definition =", "potential_node in definition['one_of']: # @RMF TODO: @Incomplete if the one of prevents extra", "Unspecified = 'Unspecified' Bool = 'Bool' Int = 'Int' Float = 'Float' String", "rmf todo: @Incomplete this shouldn't use definition['type'], it should be based on explicit", "validation might fail when it should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node):", "Array = 'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers = { 'type',", "return type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context,", "definition): if 'length' in definition: length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type", "if (length_type == RootTypes.Int): if (len(data) != length_value): return False else if (length_type", "= type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition =", "checked_types = set() while (type_name != None): if (type_name in BasicTypes): return type_name", "self.data_type = data_type self.value = value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition):", "important, but requires partial validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete will", "return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else:", "multiple types if not definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context, data,", "a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type", "context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in", "if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements'", "def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use definition['type'], it should", "definition): self.data_type = data_type self.value = value self.definition = definition def ValitateTypeMatch(context, data,", "AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends', # rmf todo: this is", "= type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this doesn't support extending either", "self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type ==", "re.match(definition['regex']): return False if 'one_of' in definition: found = False for potential_node in", ": GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString } class", "definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition", "return False if 'elements' in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if", "= GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in data: if not Validate(context,", "== RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else if", "else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions:", "else: return False if 'min' in definition: if data < definition['min']: return False", "when it should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True", "self.value = value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition)", "in definition: if data > definition['max']: return False if 'regex' in definition: if", "isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name", "if (validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success =", "objects pass LogValidationCheck(data, type_name, success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data,", "if 'one_of' in definition: found = False for potential_node in definition['one_of']: # @RMF", "definition: if not re.match(definition['regex']): return False if 'one_of' in definition: found = False", "this doesn't support extending either array or string, I think. if (root_type in", "return None def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value =", "\" to be of type \" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value", "def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition", "(len(data) != length_value): return False else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context,", ": (basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes", "RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int :", "if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that is data value\")", "#rmf todo: this doesn't support extending either array or string, I think. if", "if 'regex' in definition: if not re.match(definition['regex']): return False if 'one_of' in definition:", "length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) != length_value): return False", "be nested 'members', 'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType = {", "= 'Object' Any = 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends',", "False else if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition)", "extending either array or string, I think. if (root_type in BasicTypes): success =", "element in data: if not Validate(context, element, elements_type): return False else if (elements_type", "self.definition = definition class DataNode(): def __init__(self, data_type, value, definition): self.data_type = data_type", "type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data): return", "LogError(\"Unknown type name \" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends'", "elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in data: if not", "type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict):", "('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if", "if data < definition['min']: return False if 'max' in definition: if data >", "if ('extends' in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set()", "isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition)", "(int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object : (dict),", "class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int = 'Int' Float =", "definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if", "= ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't", "not ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in definition: if definition['type'] in", "type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return", "potential_node): found = True break if not found: return False return True def", "parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this", "checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type'", "RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else if (type_name", "that is data value\") LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name] root_type", "'extends', # rmf todo: this is important, but requires partial validation 'default_value', 'length',", "in definition: if data < definition['min']: return False if 'max' in definition: if", "type_name, success) return False else if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type", "definition['max']: return False if 'regex' in definition: if not re.match(definition['regex']): return False if", "'Bool' Int = 'Int' Float = 'Float' String = 'String' Array = 'Array'", "it is a definition, values should probably happen in a different loaded_ place", "<reponame>RFDaemoniac/ReadableFormattedData import re import pprint import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger,", "@RMF TODO: @Incomplete if the one of prevents extra members that are defined", "False if 'min' in definition: if data < definition['min']: return False if 'max'", "ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if not found: return False return", "in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if 'min'", "@Incomplete this shouldn't use definition['type'], it should be based on explicit extension validation_type", "validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete will need more work to", "parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use definition['type'], it", "definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for element", "= 'Unspecified' Bool = 'Bool' Int = 'Int' Float = 'Float' String =", "from parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float", "= { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean,", "data, definition['extends']): return False if 'type' in definition: if definition['type'] in RootTypeNameToPythonType: if", "(elements_type == RootTypes.String): for element in data: if not Validate(context, element, elements_type): return", "{ RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int", "class DefinitionNode(): def __init__(self, definition): self.definition = definition class DataNode(): def __init__(self, data_type,", "found: return False return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition:", "return False else: return False if 'min' in definition: if data < definition['min']:", "def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \"", "definition, values should probably happen in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name],", "context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete allow extending multiple types if", "= definition class DataNode(): def __init__(self, data_type, value, definition): self.data_type = data_type self.value", "in definition: length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if", "that are defined outside of one_of then this validation might fail when it", "this shouldn't use definition['type'], it should be based on explicit extension validation_type =", "success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context,", "= context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False else", "# rmf todo: @Incomplete this shouldn't use definition['type'], it should be based on", "else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf", "validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name in", "in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition]", "#rmf todo: @incomplete allow extending multiple types if not definition['extends'] in context.loaded_definitions: return", "if 'type' in definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return", "data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition if", "dict)): LogError(\"Tried to validate against type that is data value\") LogValidationCheck(data, type_name, success)", "(root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete", "= context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name", "False return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value =", "# rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success) return False def", "'required', 'delete_members' # from parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int", "values should probably happen in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)):", "context.loaded_definitions): #rmf todo: @incomplete it's not just about whether it's a dict, but", "GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int", "Object = 'Object' Any = 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex',", "BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \" + string_buffer + \" to", "'one_of' in definition: found = False for potential_node in definition['one_of']: # @RMF TODO:", "= data_type self.value = value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type", "todo: @Incomplete this shouldn't use definition['type'], it should be based on explicit extension", "Bool = 'Bool' Int = 'Int' Float = 'Float' String = 'String' Array", "= 'Bool' Int = 'Int' Float = 'Float' String = 'String' Array =", "} class DefinitionNode(): def __init__(self, definition): self.definition = definition class DataNode(): def __init__(self,", "LogError(\"Expected value \" + string_buffer + \" to be of type \" +", "return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if", "BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String", "(validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else", "type_name if (type_name in checked_types): return None # prevent circular references checked_types.add(type_name) if", "'Float' String = 'String' Array = 'Array' Object = 'Object' Any = 'Any'", "type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \" + string_buffer", "type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data,", "if 'min' in definition: if data < definition['min']: return False if 'max' in", "(length_type == RootTypes.Int): if (len(data) != length_value): return False else if (length_type ==", "!= length_value): return False else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data),", "success else if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's not just about", "not found: return False return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in", "return False return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value", "context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False else if", "might fail when it should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found", "{ 'type', 'min', 'max', 'regex', 'extends', # rmf todo: this is important, but", "'String' Array = 'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers = {", "(list), RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes = { RootTypes.Bool, RootTypes.Int,", "= ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete validate objects pass LogValidationCheck(data,", "todo: @incomplete it's not just about whether it's a dict, but whether it", "return type_name return None def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name):", "return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \" +", "None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value", ": (list), RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes = { RootTypes.Bool,", "if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if 'min' in definition:", "data, definition): if 'length' in definition: length_value = definition['length'] length_type = GetBasicType(length_value) if", "== RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in definition:", "be based on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name", "return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success)", "GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success", "'regex' in definition: if not re.match(definition['regex']): return False if 'one_of' in definition: found", "= 'String' Array = 'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers =", "def __init__(self, definition): self.definition = definition class DataNode(): def __init__(self, data_type, value, definition):", "else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion): return", "definition) #rmf todo: this doesn't support extending either array or string, I think.", "else if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's not just about whether", "if (type_name in BasicTypes): return type_name if (type_name in checked_types): return None #", "GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int = 'Int'", "RootTypes.Float : GetFloat, RootTypes.String : GetString } class DefinitionNode(): def __init__(self, definition): self.definition", "import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified'", "RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data,", "__init__(self, definition): self.definition = definition class DataNode(): def __init__(self, data_type, value, definition): self.data_type", "BasicTypes): return type_name if (type_name in checked_types): return None # prevent circular references", "return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return", "array or string, I think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data,", "= type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success)", "LogError(\"Tried to validate against type that is data value\") LogValidationCheck(data, type_name, success) return", "ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def", "nested 'members', 'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType = { RootTypes.Bool", "False if 'one_of' in definition: found = False for potential_node in definition['one_of']: #", "False else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False", "False for potential_node in definition['one_of']: # @RMF TODO: @Incomplete if the one of", "return success else if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's not just", "== RootTypes.String): for element in data: if not Validate(context, element, elements_type): return False", "RootTypes.String : GetString } class DefinitionNode(): def __init__(self, definition): self.definition = definition class", "return False if 'type' in definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data,", "context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name =", "if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in definition: elements_value =", "if (parsed_value == None): LogError(\"Expected value \" + string_buffer + \" to be", "in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while (type_name", ": (bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array :", ": (dict), RootTypes.Any : () } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String", "data, potential_node): found = True break if not found: return False return True", "is important, but requires partial validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete", "return False else if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data,", "GetRootType(data, definition) #rmf todo: this doesn't support extending either array or string, I", "todo: this doesn't support extending either array or string, I think. if (root_type", "about whether it's a dict, but whether it is a definition, values should", "validate objects pass LogValidationCheck(data, type_name, success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context,", "ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True else:", "type_name): if (type_name == RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data):", "definition['extends']): return False if 'type' in definition: if definition['type'] in RootTypeNameToPythonType: if not", "False if 'elements' in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type", "DataNode(): def __init__(self, data_type, value, definition): self.data_type = data_type self.value = value self.definition", "Int = 'Int' Float = 'Float' String = 'String' Array = 'Array' Object", "definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']): return False if", "ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \" +", "this able to be nested 'members', 'name', 'required', 'delete_members' # from parent }", "type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in", "defined outside of one_of then this validation might fail when it should actually", "type_name, success) return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data,", "set() while (type_name != None): if (type_name in BasicTypes): return type_name if (type_name", "root_type = GetRootType(data, definition) #rmf todo: this doesn't support extending either array or", "= 'Float' String = 'String' Array = 'Array' Object = 'Object' Any =", "to be nested 'members', 'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType =", "= set() while (type_name != None): if (type_name in BasicTypes): return type_name if", "success) return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name,", "# rmf todo: this is important, but requires partial validation 'default_value', 'length', 'one_of',", "type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name,", "whether it is a definition, values should probably happen in a different loaded_", "data_type, value, definition): self.data_type = data_type self.value = value self.definition = definition def", "data value\") LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context,", "type_defintion): return type_definition['type'] else if ('extends' in type_defition): type_name = type_defintion['extends'] else: return", "validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition else if (validation_type", "against type that is data value\") LogValidationCheck(data, type_name, success) return False definition =", "type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def", "'length' in definition: length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int):", "(validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data,", "RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString } class DefinitionNode(): def", "not re.match(definition['regex']): return False if 'one_of' in definition: found = False for potential_node", "return type_definition['type'] else if ('extends' in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified", "definition: if data < definition['min']: return False if 'max' in definition: if data", "place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that is data", "# from parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int : (int),", "if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo:", "todo: @incomplete allow extending multiple types if not definition['extends'] in context.loaded_definitions: return False", "== RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name)", "(float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any : ()", "this is important, but requires partial validation 'default_value', 'length', 'one_of', # rmf todo:", "should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if", "think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type", "data > definition['max']: return False if 'regex' in definition: if not re.match(definition['regex']): return", "ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value = definition['length'] length_type = GetBasicType(length_value)", "('type' in type_defintion): return type_definition['type'] else if ('extends' in type_defition): type_name = type_defintion['extends']", "RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object", "(type_name in RootTypeNameToPythonType): success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else", "value \" + string_buffer + \" to be of type \" + type_name)", "= definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) != length_value):", "root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False else if (validation_type", "!= None): if (type_name in BasicTypes): return type_name if (type_name in checked_types): return", "@incomplete will need more work to make this able to be nested 'members',", "to be of type \" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value def", "(type_name in BasicTypes): return type_name if (type_name in checked_types): return None # prevent", "RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array", "ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition)", "RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else if ('extends'", "RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool' Int = 'Int' Float = 'Float'", "one_of then this validation might fail when it should actually be valid if", "def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value = definition['length'] length_type =", "fail when it should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found =", "RootTypes.String): type_name = type_name_or_definition else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if", "string, I think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else", "type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition", "= 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends', # rmf todo:", "TODO: @Incomplete if the one of prevents extra members that are defined outside", "definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in data: if", "'max', 'regex', 'extends', # rmf todo: this is important, but requires partial validation", "type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this doesn't support extending either array", "String = 'String' Array = 'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers", "definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name", "= GetRootType(data, definition) #rmf todo: this doesn't support extending either array or string,", "parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float :", "else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if", "not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return", "@Incomplete if the one of prevents extra members that are defined outside of", "data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType:", "for potential_node in definition['one_of']: # @RMF TODO: @Incomplete if the one of prevents", "in definition: #rmf todo: @incomplete allow extending multiple types if not definition['extends'] in", "Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any):", "'max' in definition: if data > definition['max']: return False if 'regex' in definition:", "(ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data): return (GetBasicType(data) != None) def", "this validation might fail when it should actually be valid if ValidateDefinitionOfBasicType(context, data,", "extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition else if", "= GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name in RootTypeNameToPythonType):", "if (len(data) != length_value): return False else if (length_type == RootTypes.Object): if not", "'default_value', 'length', 'one_of', # rmf todo: @incomplete will need more work to make", "data: if not Validate(context, element, elements_type): return False else if (elements_type == RootTypes.Object):", "if data > definition['max']: return False if 'regex' in definition: if not re.match(definition['regex']):", "{ RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString", "else if ('extends' in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types =", "re import pprint import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat,", "the one of prevents extra members that are defined outside of one_of then", "None # prevent circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None", "GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString } class DefinitionNode():", "= { RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String :", "doesn't support extending either array or string, I think. if (root_type in BasicTypes):", "of one_of then this validation might fail when it should actually be valid", "(parsed_value == None): LogError(\"Expected value \" + string_buffer + \" to be of", "string_buffer + \" to be of type \" + type_name) parsed_value = ParseValue(string_buffer)", "if (type_name not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type' in", "if ('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition):", "checked_types): return None # prevent circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions):", "length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) !=", "if not ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in definition: if definition['type']", ": (int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object :", "to make this able to be nested 'members', 'name', 'required', 'delete_members' # from", "(bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String : (basestring), RootTypes.Array : (list),", "type \" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): #", "{ RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String : (basestring),", "data, definition) else: # rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success)", "type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True", "it should be based on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type ==", "== RootTypes.String): type_name = type_name_or_definition else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition", "data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True else: return", "RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String : GetString }", "todo: this is important, but requires partial validation 'default_value', 'length', 'one_of', # rmf", "= 'Int' Float = 'Float' String = 'String' Array = 'Array' Object =", "in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def IsBasicType(data): return (GetBasicType(data)", "= type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not", "I think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if", "in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against", "'Array' Object = 'Object' Any = 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max',", "'Object' Any = 'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends', #", "not in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return False definition =", "found = True break if not found: return False return True def ValidateDefinitionOfArrayType(context,", "type_name, success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data,", "type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return", "return False else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return", "False if 'regex' in definition: if not re.match(definition['regex']): return False if 'one_of' in", "success) return False def Validate(context, data, type_name_or_definition): ValitateTypeMatch(context, data, type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name):", "ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition))", "not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in definition: elements_value = definition['elements']", "pprint import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue", "(type_name in checked_types): return None # prevent circular references checked_types.add(type_name) if (type_name not", "@incomplete it's not just about whether it's a dict, but whether it is", "return False if 'max' in definition: if data > definition['max']: return False if", "= type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else if ('extends' in type_defition):", "True break if not found: return False return True def ValidateDefinitionOfArrayType(context, data, definition):", "type_definition['type'] else if ('extends' in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types", "found = False for potential_node in definition['one_of']: # @RMF TODO: @Incomplete if the", "= { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat, RootTypes.String :", "False if not ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in definition: if", "} BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float : GetFloat,", "should probably happen in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried", "'regex', 'extends', # rmf todo: this is important, but requires partial validation 'default_value',", "definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name) else: LogValidationCheck(data, type_name, success) return False", "ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete this shouldn't use", "ValidateTypeMatch(context, data, definition['extends']): return False if 'type' in definition: if definition['type'] in RootTypeNameToPythonType:", "it should actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break", "requires partial validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete will need more", "GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None def", "Float = 'Float' String = 'String' Array = 'Array' Object = 'Object' Any", "in definition: found = False for potential_node in definition['one_of']: # @RMF TODO: @Incomplete", "value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type", "# rmf todo: @incomplete will need more work to make this able to", "__init__(self, data_type, value, definition): self.data_type = data_type self.value = value self.definition = definition", "definition class DataNode(): def __init__(self, data_type, value, definition): self.data_type = data_type self.value =", "RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this doesn't support", "@incomplete validate objects pass LogValidationCheck(data, type_name, success) return False def Validate(context, data, type_name_or_definition):", "('extends' in type_defition): type_name = type_defintion['extends'] else: return RootTypes.Unspecified checked_types = set() while", "shouldn't use definition['type'], it should be based on explicit extension validation_type = GetBasicType(type_name_or_definition)", "return True def ValidateDefinitionOfArrayType(context, data, definition): if 'length' in definition: length_value = definition['length']", "GetFloat, RootTypes.String : GetString } class DefinitionNode(): def __init__(self, definition): self.definition = definition", "more work to make this able to be nested 'members', 'name', 'required', 'delete_members'", ": GetString } class DefinitionNode(): def __init__(self, definition): self.definition = definition class DataNode():", "LogValidationCheck(data, type_name, success) return success else if (type_name in context.loaded_definitions): #rmf todo: @incomplete", "todo: @incomplete will need more work to make this able to be nested", "else: return RootTypes.Unspecified checked_types = set() while (type_name != None): if (type_name in", "either array or string, I think. if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context,", "== RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in", "in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name", "dict, but whether it is a definition, values should probably happen in a", "type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return", "def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return None", "import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class", "(validation_type == RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this", "+ type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo:", "in definition['one_of']: # @RMF TODO: @Incomplete if the one of prevents extra members", "not definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']): return False", "in checked_types): return None # prevent circular references checked_types.add(type_name) if (type_name not in", "'Any' AllowedDefinitionMembers = { 'type', 'min', 'max', 'regex', 'extends', # rmf todo: this", "return RootTypes.Unspecified checked_types = set() while (type_name != None): if (type_name in BasicTypes):", "context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if", "ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in definition: elements_value = definition['elements'] elements_type", "in data: if not Validate(context, element, elements_type): return False else if (elements_type ==", "if not definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']): return", "RootTypeNameToPythonType = { RootTypes.Bool : (bool), RootTypes.Int : (int), RootTypes.Float : (float), RootTypes.String", "ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition", "\" + type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf", "definition['length'] length_type = GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) != length_value): return", "if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown", "GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool = 'Bool'", "@incomplete allow extending multiple types if not definition['extends'] in context.loaded_definitions: return False if", "success) return False else if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type =", "+ str(type_name_or_definition)) return False definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo:", "(not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that is data value\") LogValidationCheck(data,", "type_name) parsed_value = ParseValue(string_buffer) return parsed_value def GetRootType(context, type_name_or_defintion): # rmf todo: @Incomplete", "happen in a different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate", "return False if 'regex' in definition: if not re.match(definition['regex']): return False if 'one_of'", "if 'extends' in definition: #rmf todo: @incomplete allow extending multiple types if not", "'Unspecified' Bool = 'Bool' Int = 'Int' Float = 'Float' String = 'String'", "None): if (type_name in BasicTypes): return type_name if (type_name in checked_types): return None", "== RootTypes.Array): success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete validate", "in definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else:", "valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if not found: return", "based on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name =", "are defined outside of one_of then this validation might fail when it should", "#rmf todo: @incomplete it's not just about whether it's a dict, but whether", "definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return", "but requires partial validation 'default_value', 'length', 'one_of', # rmf todo: @incomplete will need", "success) return success else if (type_name in context.loaded_definitions): #rmf todo: @incomplete it's not", "else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)):", "type_name_or_definition) def ValidateBuiltinTypeMatch(data, type_name): if (type_name == RootTypes.Any): return True else: return isinstance(data,", "will need more work to make this able to be nested 'members', 'name',", "LogError, GetInteger, GetBoolean, GetFloat, GetString, ParseValue class RootTypes(): Unspecified = 'Unspecified' Bool =", "value\") LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name] root_type = GetRootType(context, type_name)", "GetString } class DefinitionNode(): def __init__(self, definition): self.definition = definition class DataNode(): def", "if ('type' in type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends']", "'type' in definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False", "if the one of prevents extra members that are defined outside of one_of", "definition['one_of']: # @RMF TODO: @Incomplete if the one of prevents extra members that", "RootTypes.Int): if (len(data) != length_value): return False else if (length_type == RootTypes.Object): if", "length_value): return False else if (length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']):", "return type_name if (type_name in checked_types): return None # prevent circular references checked_types.add(type_name)", "if 'length' in definition: length_value = definition['length'] length_type = GetBasicType(length_value) if (length_type ==", "= type_name_or_definition else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type' in", "True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data,", "BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type == RootTypes.Array): success =", "if ('type' in type_defintion): return type_definition['type'] else if ('extends' in type_defition): type_name =", "in type_defintion): return type_definition['type'] if ('extends' in type_defintion) type_name = type_defintion['extends'] return RootTypes.Unspecified", "type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type name \" + str(type_name_or_definition)) return False definition", "return False if 'one_of' in definition: found = False for potential_node in definition['one_of']:", "'name', 'required', 'delete_members' # from parent } RootTypeNameToPythonType = { RootTypes.Bool : (bool),", ": (float), RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any :", "= BasicTypeParsers[type_name](string_buffer) if (parsed_value == None): LogError(\"Expected value \" + string_buffer + \"", "type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data, type_name_or_definition) if type_name_or_definition not in context.loaded_definitions: LogError(\"Unknown type", "'elements' in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String):", "type_name = type_name_or_definition else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type'", "type_name_or_definition if ('type' in type_defintion): return type_definition['type'] else if ('extends' in type_defition): type_name", "== None): LogError(\"Expected value \" + string_buffer + \" to be of type", "circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name]", "a definition, values should probably happen in a different loaded_ place if (not", "= value self.definition = definition def ValitateTypeMatch(context, data, type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if", "ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition in", "= definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for element in data:", "return None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if ('extends'", "RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any : () } BasicTypes = {", "RootTypes.String : (basestring), RootTypes.Array : (list), RootTypes.Object : (dict), RootTypes.Any : () }", "IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if (parsed_value", "= context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete allow extending multiple types", "\" + string_buffer + \" to be of type \" + type_name) parsed_value", "= GetBasicType(length_value) if (length_type == RootTypes.Int): if (len(data) != length_value): return False else", "success = ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else if (type_name in", "import pprint import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean, GetFloat, GetString,", "False if 'max' in definition: if data > definition['max']: return False if 'regex'", "type_name_or_definition else if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion):", "< definition['min']: return False if 'max' in definition: if data > definition['max']: return", "definition['type'], it should be based on explicit extension validation_type = GetBasicType(type_name_or_definition) if (validation_type", "in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type == RootTypes.String): for", "definition: found = False for potential_node in definition['one_of']: # @RMF TODO: @Incomplete if", "= ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else if (type_name in context.loaded_definitions):", "success = ValidateDefinitionOfArrayType(context, data, definition) else: # rmf todo: @incomplete validate objects pass", "loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that is", "RootTypes.Unspecified def ValidateDefinitionOfBasicType(context, data, type_name_or_definition): if isinstance(definition, dict): definition = type_name_or_definition else: if", "types if not definition['extends'] in context.loaded_definitions: return False if not ValidateTypeMatch(context, data, definition['extends']):", "definition['type']): return False else: return False if 'min' in definition: if data <", "# prevent circular references checked_types.add(type_name) if (type_name not in context.loaded_definitions): return None type_defintion", "LogValidationCheck(data, type_name, success) return False else if (validation_type == RootTypes.Object): definition = type_name_or_definition", "type_name_or_definition): validation_type = GetBasicType(type_name_or_definition) if (validation_type == RootTypes.String): type_name = type_name_or_definition if (type_name", "class DataNode(): def __init__(self, data_type, value, definition): self.data_type = data_type self.value = value", "RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']): return False else: return False if 'min' in", "RootTypes.Any : () } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers", "definition): self.definition = definition class DataNode(): def __init__(self, data_type, value, definition): self.data_type =", "if 'elements' in definition: elements_value = definition['elements'] elements_type = GetBasicType(elements_value) if (elements_type ==", "isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that is data value\") LogValidationCheck(data, type_name,", "rmf todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success) return False def Validate(context,", "RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger, RootTypes.Float :", "BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool :", "(length_type == RootTypes.Object): if not ValidateDefinitionOfBasicType(context, len(data), definition['length']): return False if 'elements' in", "if (validation_type == RootTypes.Object): definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf todo:", "ValidateBuiltinTypeMatch(data, type_name) LogValidationCheck(data, type_name, success) return success else if (type_name in context.loaded_definitions): #rmf", "(type_name in context.loaded_definitions): #rmf todo: @incomplete it's not just about whether it's a", "validate against type that is data value\") LogValidationCheck(data, type_name, success) return False definition", "import re import pprint import pdb from RFDUtilityFunctions import LogValidationCheck, LogError, GetInteger, GetBoolean,", "definition = context.loaded_definitions[type_name_or_definition] if 'extends' in definition: #rmf todo: @incomplete allow extending multiple", "False if 'type' in definition: if definition['type'] in RootTypeNameToPythonType: if not ValidateBuiltinTypeMatch(data, definition['type']):", "be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if not found:", "def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer, type_name): parsed_value = BasicTypeParsers[type_name](string_buffer) if", "if isinstance(definition, dict): definition = type_name_or_definition else: if type_name_or_definition in RootTypeNameToPythonType: return ValidateBuiltinTypeMatch(data,", "RootTypes.Unspecified checked_types = set() while (type_name != None): if (type_name in BasicTypes): return", "> definition['max']: return False if 'regex' in definition: if not re.match(definition['regex']): return False", "need more work to make this able to be nested 'members', 'name', 'required',", "RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name in BasicTypes: if (ValidateBuiltinTypeMatch(data, type_name)): return type_name return", "if (validation_type == RootTypes.Object): type_definition = type_name_or_definition if ('type' in type_defintion): return type_definition['type']", "is data value\") LogValidationCheck(data, type_name, success) return False definition = context.loaded_definitions[type_name] root_type =", "todo: @incomplete validate objects pass LogValidationCheck(data, type_name, success) return False def Validate(context, data,", "if (root_type in BasicTypes): success = ValidateDefinitionOfBasicType(context, data, definition) else if (root_type ==", "different loaded_ place if (not isinstance(context.loaded_definitions[type_name], dict)): LogError(\"Tried to validate against type that", "context.loaded_definitions): return None type_defintion = context.loaded_definitions[type_name] if ('type' in type_defintion): return type_definition['type'] if", "() } BasicTypes = { RootTypes.Bool, RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = {", "type_name)): return type_name return None def IsBasicType(data): return (GetBasicType(data) != None) def ParseTypedBasicValue(string_buffer,", "definition = type_name_or_definition root_type = GetRootType(data, definition) #rmf todo: this doesn't support extending", "RootTypes.Int, RootTypes.Float, RootTypes.String } BasicTypeParsers = { RootTypes.Bool : GetBoolean, RootTypes.Int : GetInteger,", "not just about whether it's a dict, but whether it is a definition,", "if 'max' in definition: if data > definition['max']: return False if 'regex' in", "definition['min']: return False if 'max' in definition: if data > definition['max']: return False", "'Int' Float = 'Float' String = 'String' Array = 'Array' Object = 'Object'", "(type_name == RootTypes.Any): return True else: return isinstance(data, RootTypeNameToPythonType[type_name]) def GetBasicType(data): for type_name", "if (type_name in checked_types): return None # prevent circular references checked_types.add(type_name) if (type_name", "actually be valid if ValidateDefinitionOfBasicType(context, data, potential_node): found = True break if not" ]
[ "from time import sleep from subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound,", "): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse')", "percentage_detection import threading import numpy as np import pyautogui from pyautogui import press,", "np import pyautogui from pyautogui import press, hotkey, click, scroll, typewrite, moveRel, moveTo,", "= \"regular\" self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound() moveTo( 500, 500", "hotkey, click, scroll, typewrite, moveRel, moveTo, position from time import sleep from subprocess", "turn_on_sound, mute_sound, toggle_speechrec import os import math class TwitchMode: def __init__(self, modeSwitcher): self.mode", "self ): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def", ") or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ): self.mode", "percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ): self.mode = \"regular\"", "lib.detection_strategies import single_tap_detection, loud_detection, medium_detection, percentage_detection import threading import numpy as np import", "): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input(", "import math class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher", "loud_detection, medium_detection, percentage_detection import threading import numpy as np import pyautogui from pyautogui", "hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or", "def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\",", "toggle_speechrec import os import math class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\"", "import numpy as np import pyautogui from pyautogui import press, hotkey, click, scroll,", "import single_tap_detection, loud_detection, medium_detection, percentage_detection import threading import numpy as np import pyautogui", "dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ):", "call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math class", "500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if(", "from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math class TwitchMode:", "90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ):", "math class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def", "or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ): self.mode =", "position from time import sleep from subprocess import call from lib.system_toggles import toggle_eyetracker,", "import sleep from subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec", "'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts,", "moveRel, moveTo, position from time import sleep from subprocess import call from lib.system_toggles", "press, hotkey, click, scroll, typewrite, moveRel, moveTo, position from time import sleep from", "import pyautogui from pyautogui import press, hotkey, click, scroll, typewrite, moveRel, moveTo, position", "\"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ): self.mode = \"regular\" mute_sound()", "sleep from subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import", "scroll, typewrite, moveRel, moveTo, position from time import sleep from subprocess import call", "modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound() moveTo(", "time import sleep from subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound,", "\"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit( self", "moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts", "as np import pyautogui from pyautogui import press, hotkey, click, scroll, typewrite, moveRel,", "90 ) ): self.modeSwitcher.switchMode('browse') def exit( self ): self.mode = \"regular\" mute_sound() press('esc')", "subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import", "single_tap_detection, loud_detection, medium_detection, percentage_detection import threading import numpy as np import pyautogui from", "\"regular\" self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound() moveTo( 500, 500 )", "import press, hotkey, click, scroll, typewrite, moveRel, moveTo, position from time import sleep", "from lib.detection_strategies import single_tap_detection, loud_detection, medium_detection, percentage_detection import threading import numpy as np", "= modeSwitcher def start( self ): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000,", "def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start( self ):", "self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound() moveTo( 500, 500 ) click()", "medium_detection, percentage_detection import threading import numpy as np import pyautogui from pyautogui import", "<reponame>okonomichiyaki/parrot.py<gh_stars>10-100 from lib.detection_strategies import single_tap_detection, loud_detection, medium_detection, percentage_detection import threading import numpy as", "def start( self ): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl',", "from subprocess import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os", "500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ):", "lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math class TwitchMode: def", "click, scroll, typewrite, moveRel, moveTo, position from time import sleep from subprocess import", "TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start( self", "self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound() moveTo( 500,", "import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math class TwitchMode: def __init__(self,", "os import math class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher =", "pyautogui from pyautogui import press, hotkey, click, scroll, typewrite, moveRel, moveTo, position from", "moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90", "2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 )", "__init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start( self ): turn_on_sound()", "turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self,", "pyautogui import press, hotkey, click, scroll, typewrite, moveRel, moveTo, position from time import", "from pyautogui import press, hotkey, click, scroll, typewrite, moveRel, moveTo, position from time", "click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\",", "toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math class TwitchMode: def __init__(self, modeSwitcher):", "import os import math class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher", "moveTo, position from time import sleep from subprocess import call from lib.system_toggles import", "if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def", "start( self ): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000) hotkey('ctrl', 'f')", "self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 )", "threading import numpy as np import pyautogui from pyautogui import press, hotkey, click,", "import threading import numpy as np import pyautogui from pyautogui import press, hotkey,", "percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90 ) ): self.modeSwitcher.switchMode('browse') def exit(", "numpy as np import pyautogui from pyautogui import press, hotkey, click, scroll, typewrite,", "modeSwitcher def start( self ): turn_on_sound() moveTo( 500, 500 ) click() moveTo(2000, 2000)", "handle_input( self, dataDicts ): if( percentage_detection(dataDicts, \"whistle\", 90 ) or percentage_detection(dataDicts, \"bell\", 90", "mute_sound, toggle_speechrec import os import math class TwitchMode: def __init__(self, modeSwitcher): self.mode =", "class TwitchMode: def __init__(self, modeSwitcher): self.mode = \"regular\" self.modeSwitcher = modeSwitcher def start(", "import call from lib.system_toggles import toggle_eyetracker, turn_on_sound, mute_sound, toggle_speechrec import os import math", "typewrite, moveRel, moveTo, position from time import sleep from subprocess import call from", ") click() moveTo(2000, 2000) hotkey('ctrl', 'f') def handle_input( self, dataDicts ): if( percentage_detection(dataDicts," ]
[ "file child = 0 if player == \"vlc\": opt = '--play-and-exit' else: opt", "currently playing? player = \"omxplayer\" # The video player being used video_path =", "player = \"omxplayer\" # The video player being used video_path = \"/home/pi/video.mp4\" #", "GPIO import time import subprocess import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD)", "0 if player == \"vlc\": opt = '--play-and-exit' else: opt = '' try:", "GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running", "PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN)", "Is a video currently playing? player = \"omxplayer\" # The video player being", "# Path to video file child = 0 if player == \"vlc\": opt", "main.py # import RPi.GPIO as GPIO import time import subprocess import os PIR_PIN", "for motion\") while True: if not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\")", "# Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a", "if running == True: child.poll() if child.returncode == 0: running = False print(\"Video", "= \"omxplayer\" # The video player being used video_path = \"/home/pi/video.mp4\" # Path", "if running == False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running =", "== 0: running = False print(\"Video complete, waiting for motion\") time.sleep(1) except KeyboardInterrupt:", "# GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False", "as GPIO import time import subprocess import os PIR_PIN = 11 # GPIO11", "= '--play-and-exit' else: opt = '' try: print(\"Waiting for motion\") while True: if", "to video file child = 0 if player == \"vlc\": opt = '--play-and-exit'", "# Is a video currently playing? player = \"omxplayer\" # The video player", "import time import subprocess import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) #", "11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running =", "opt]) running = True print(\"Playing video\") if running == True: child.poll() if child.returncode", "else: opt = '' try: print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN):", "= \"/home/pi/video.mp4\" # Path to video file child = 0 if player ==", "time import subprocess import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use", "being used video_path = \"/home/pi/video.mp4\" # Path to video file child = 0", "'' try: print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN): if running ==", "numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a video currently playing? player", "== True: child.poll() if child.returncode == 0: running = False print(\"Video complete, waiting", "child = subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\") if running ==", "motion\") while True: if not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child", "\"/home/pi/video.mp4\" # Path to video file child = 0 if player == \"vlc\":", "# -*- coding: utf-8 -*- # # main.py # import RPi.GPIO as GPIO", "-*- # # main.py # import RPi.GPIO as GPIO import time import subprocess", "print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\") if", "os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN,", "running = False print(\"Video complete, waiting for motion\") time.sleep(1) except KeyboardInterrupt: print(\"Quit\") GPIO.cleanup()", "subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\") if running == True: child.poll()", "try: print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN): if running == False:", "# The video player being used video_path = \"/home/pi/video.mp4\" # Path to video", "The video player being used video_path = \"/home/pi/video.mp4\" # Path to video file", "used video_path = \"/home/pi/video.mp4\" # Path to video file child = 0 if", "detected\") child = subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\") if running", "GPIO.IN) running = False # Is a video currently playing? player = \"omxplayer\"", "if child.returncode == 0: running = False print(\"Video complete, waiting for motion\") time.sleep(1)", "# # main.py # import RPi.GPIO as GPIO import time import subprocess import", "= '' try: print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN): if running", "child.returncode == 0: running = False print(\"Video complete, waiting for motion\") time.sleep(1) except", "'--play-and-exit' else: opt = '' try: print(\"Waiting for motion\") while True: if not", "print(\"Playing video\") if running == True: child.poll() if child.returncode == 0: running =", "if player == \"vlc\": opt = '--play-and-exit' else: opt = '' try: print(\"Waiting", "# main.py # import RPi.GPIO as GPIO import time import subprocess import os", "player being used video_path = \"/home/pi/video.mp4\" # Path to video file child =", "header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a video currently", "-*- coding: utf-8 -*- # # main.py # import RPi.GPIO as GPIO import", "= False # Is a video currently playing? player = \"omxplayer\" # The", "= True print(\"Playing video\") if running == True: child.poll() if child.returncode == 0:", "utf-8 -*- # # main.py # import RPi.GPIO as GPIO import time import", "import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers", "False # Is a video currently playing? player = \"omxplayer\" # The video", "while True: if not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child =", "subprocess import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin", "= 0 if player == \"vlc\": opt = '--play-and-exit' else: opt = ''", "True: if not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child = subprocess.Popen([player,", "== \"vlc\": opt = '--play-and-exit' else: opt = '' try: print(\"Waiting for motion\")", "# import RPi.GPIO as GPIO import time import subprocess import os PIR_PIN =", "running = True print(\"Playing video\") if running == True: child.poll() if child.returncode ==", "child.poll() if child.returncode == 0: running = False print(\"Video complete, waiting for motion\")", "video_path, opt]) running = True print(\"Playing video\") if running == True: child.poll() if", "opt = '--play-and-exit' else: opt = '' try: print(\"Waiting for motion\") while True:", "playing? player = \"omxplayer\" # The video player being used video_path = \"/home/pi/video.mp4\"", "\"vlc\": opt = '--play-and-exit' else: opt = '' try: print(\"Waiting for motion\") while", "print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN): if running == False: print(\"Motion", "running == False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running = True", "0: running = False print(\"Video complete, waiting for motion\") time.sleep(1) except KeyboardInterrupt: print(\"Quit\")", "running = False # Is a video currently playing? player = \"omxplayer\" #", "GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False #", "= subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\") if running == True:", "GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is", "Path to video file child = 0 if player == \"vlc\": opt =", "False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running = True print(\"Playing video\")", "RPi.GPIO as GPIO import time import subprocess import os PIR_PIN = 11 #", "#!/usr/bin/env python # -*- coding: utf-8 -*- # # main.py # import RPi.GPIO", "pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a video currently playing?", "== False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt]) running = True print(\"Playing", "player == \"vlc\": opt = '--play-and-exit' else: opt = '' try: print(\"Waiting for", "video file child = 0 if player == \"vlc\": opt = '--play-and-exit' else:", "video currently playing? player = \"omxplayer\" # The video player being used video_path", "\"omxplayer\" # The video player being used video_path = \"/home/pi/video.mp4\" # Path to", "video player being used video_path = \"/home/pi/video.mp4\" # Path to video file child", "import RPi.GPIO as GPIO import time import subprocess import os PIR_PIN = 11", "= 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running", "Use header pin numbers GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a video", "video_path = \"/home/pi/video.mp4\" # Path to video file child = 0 if player", "coding: utf-8 -*- # # main.py # import RPi.GPIO as GPIO import time", "child = 0 if player == \"vlc\": opt = '--play-and-exit' else: opt =", "not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child = subprocess.Popen([player, video_path, opt])", "if not GPIO.input(PIR_PIN): if running == False: print(\"Motion detected\") child = subprocess.Popen([player, video_path,", "opt = '' try: print(\"Waiting for motion\") while True: if not GPIO.input(PIR_PIN): if", "video\") if running == True: child.poll() if child.returncode == 0: running = False", "True: child.poll() if child.returncode == 0: running = False print(\"Video complete, waiting for", "python # -*- coding: utf-8 -*- # # main.py # import RPi.GPIO as", "running == True: child.poll() if child.returncode == 0: running = False print(\"Video complete,", "GPIO.setup(PIR_PIN, GPIO.IN) running = False # Is a video currently playing? player =", "import subprocess import os PIR_PIN = 11 # GPIO11 GPIO.setmode(GPIO.BOARD) # Use header", "True print(\"Playing video\") if running == True: child.poll() if child.returncode == 0: running", "a video currently playing? player = \"omxplayer\" # The video player being used" ]
[ "'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project number", "KIND, either express or implied. # See the License for the specific language", "= FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance = load_config_from_path(config_class,", "Unless required by applicable law or agreed to in writing, software # distributed", "+= 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done:", "from builtins import range from csv import DictWriter from json import load as", "type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required", "not chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider", "query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return", "\"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type =", "logging from io import StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\")", "type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path,", "and # limitations under the License. ### from __future__ import print_function from future", "this file except in compliance with the License. # You may obtain a", "result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass", "json import load as load_json import logging from io import StringIO from time", "standard_library.install_aliases() from builtins import str from builtins import range from csv import DictWriter", "for completion while all_done is False and total_retries < poll_retry_limit: poll_count += 1", "ANY KIND, either express or implied. # See the License for the specific", "as load_json import logging from io import StringIO from time import sleep import", "run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done", "def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME", "Systems Biology # # Licensed under the Apache License, Version 2.0 (the \"License\");", "1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done}", "range from csv import DictWriter from json import load as load_json import logging", "sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils import", "= run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query)", "= provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance)", "= FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json", "chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path))", "= provider.build_query(config_instance) print(query) # project_id: project number of the BQ data project (typically", "bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def", "@click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str", "OF ANY KIND, either express or implied. # See the License for the", "= provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict)", "# limitations under the License. ### from __future__ import print_function from future import", "import standard_library standard_library.install_aliases() from builtins import str from builtins import range from csv", "under the License. ### from __future__ import print_function from future import standard_library standard_library.install_aliases()", "builtins import str from builtins import range from csv import DictWriter from json", "load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x", "chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project", "include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command()", "type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type,", "BQ data project (typically isb-cgc's project number) # data_type: 4-letter data type code,", "load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames", "provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project number of the BQ", "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def", "chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider =", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "language governing permissions and # limitations under the License. ### from __future__ import", "config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False", "data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json',", "# data_type: 4-letter data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str)", "provider.build_query(config_instance) print(query) # project_id: project number of the BQ data project (typically isb-cgc's", "= [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\")", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "project number of the BQ data project (typically isb-cgc's project number) # data_type:", "def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w')", "return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x in schema]", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "\"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array):", "logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def", "def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False):", "writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header)", "required by applicable law or agreed to in writing, software # distributed under", "methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type)))", "file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required", "applicable law or agreed to in writing, software # distributed under the License", "{}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance", "DictWriter from json import load as load_json import logging from io import StringIO", "= is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result", "django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config):", "print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class", "or agreed to in writing, software # distributed under the License is distributed", "from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range", "StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import", "0 # Poll for completion while all_done is False and total_retries < poll_retry_limit:", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "data_type: 4-letter data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path',", "= load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for", "not chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else:", "file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type',", "Copyright 2015-2019, Institute for Systems Biology # # Licensed under the Apache License,", "fieldnames = [x['name'] for x in schema] file_obj = StringIO() writer = DictWriter(file_obj,", "[x['name'] for x in schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "load_json import logging from io import StringIO from time import sleep import os", "click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id)", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "import print_function from future import standard_library standard_library.install_aliases() from builtins import str from builtins", "provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0", "'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x in", "multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type =", "License. # You may obtain a copy of the License at # #", "config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance =", "1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries))", "= FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for c", "save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run) if __name__ ==", "import StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup()", "poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count = 0 #", "type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str)", "= [x['name'] for x in schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames)", "print_function from future import standard_library standard_library.install_aliases() from builtins import str from builtins import", "= provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result =", "compliance with the License. # You may obtain a copy of the License", "schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle:", "@click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def", "feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if", "[str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query", "in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array)", "time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from", "config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X',", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "# project_id: project number of the BQ data project (typically isb-cgc's project number)", "4-letter data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str)", "query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema,", "the License. ### from __future__ import print_function from future import standard_library standard_library.install_aliases() from", "future import standard_library standard_library.install_aliases() from builtins import str from builtins import range from", "False and total_retries < poll_retry_limit: poll_count += 1 total_retries += 1 is_finished =", "import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference =", "data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type)", "chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array", "poll_retry_limit: poll_count += 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished", "### from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import", "not use this file except in compliance with the License. # You may", "FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict =", "= provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project number of the", "isb-cgc's project number) # data_type: 4-letter data type code, eg. GNAB @click.command() @click.argument('project_id',", "= FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict", "License, Version 2.0 (the \"License\"); # you may not use this file except", "= provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count =", "= DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count", "'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True,", "DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False):", "writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema,", "import str from builtins import range from csv import DictWriter from json import", "limitations under the License. ### from __future__ import print_function from future import standard_library", "# you may not use this file except in compliance with the License.", "schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return", "include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr',", "# Poll for completion while all_done is False and total_retries < poll_retry_limit: poll_count", "agreed to in writing, software # distributed under the License is distributed on", "schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str)", "FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time", "io import StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django", "(the \"License\"); # you may not use this file except in compliance with", "logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not", "logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path,", "chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project number of the BQ data", "config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not", "# Unless required by applicable law or agreed to in writing, software #", "all_done is False and total_retries < poll_retry_limit: poll_count += 1 total_retries += 1", "logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path):", "None: config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if", "def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class", "by applicable law or agreed to in writing, software # distributed under the", "FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance = load_config_from_path(config_class, config_json)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome", "provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result()", "number of the BQ data project (typically isb-cgc's project number) # data_type: 4-letter", "query = provider.build_query(config_instance) print(query) # project_id: project number of the BQ data project", "with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\",", "poll_count = 0 # Poll for completion while all_done is False and total_retries", "chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type)", "all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return", "= get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str)", "file except in compliance with the License. # You may obtain a copy", "import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils", "provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result,", "governing permissions and # limitations under the License. ### from __future__ import print_function", "License for the specific language governing permissions and # limitations under the License.", "= load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array:", "data project (typically isb-cgc's project number) # data_type: 4-letter data type code, eg.", "provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done =", "'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config:", "to in writing, software # distributed under the License is distributed on an", "= False total_retries = 0 poll_count = 0 # Poll for completion while", "implied. # See the License for the specific language governing permissions and #", "= config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for c in range(1, 23)]", "\"License\"); # you may not use this file except in compliance with the", "the BQ data project (typically isb-cgc's project number) # data_type: 4-letter data type", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "(required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type)))", "while all_done is False and total_retries < poll_retry_limit: poll_count += 1 total_retries +=", "@click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json,", "__future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from", "@click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for", "config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run) if __name__", "or implied. # See the License for the specific language governing permissions and", "config_json is not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance", "the specific language governing permissions and # limitations under the License. ### from", "from csv import DictWriter from json import load as load_json import logging from", "def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x in schema] file_obj =", "chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array =", "job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "is False and total_retries < poll_retry_limit: poll_count += 1 total_retries += 1 is_finished", "provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count = 0", "specific language governing permissions and # limitations under the License. ### from __future__", "not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict)", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id,", "print(query) # project_id: project number of the BQ data project (typically isb-cgc's project", "config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name']", "range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) #", "@click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome", "False total_retries = 0 poll_count = 0 # Poll for completion while all_done", "fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj", "get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json',", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance)", "import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES", "you may not use this file except in compliance with the License. #", "else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c)", "Institute for Systems Biology # # Licensed under the Apache License, Version 2.0", "sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class,", "help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type)", "os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO)", "chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(),", "@click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\")", "if not chromosome_array: chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y'])", "use this file except in compliance with the License. # You may obtain", "provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None: config_instance = load_config_from_path(config_class, config_json) else:", "csv import DictWriter from json import load as load_json import logging from io", "@click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path, config_json,", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "import load as load_json import logging from io import StringIO from time import", "= 0 poll_count = 0 # Poll for completion while all_done is False", "config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x in schema] file_obj", "+= 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done),", "retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r'))", "if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj =", "23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV:", "csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class", "builtins import range from csv import DictWriter from json import load as load_json", "import DictWriter from json import load as load_json import logging from io import", "from json import load as load_json import logging from io import StringIO from", "2.0 (the \"License\"); # you may not use this file except in compliance", "config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for", "is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def", "of the BQ data project (typically isb-cgc's project number) # data_type: 4-letter data", "project (typically isb-cgc's project number) # data_type: 4-letter data type code, eg. GNAB", "return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with", "save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as", "config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows, schema, include_header=False): fieldnames =", "License. ### from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins", "### # Copyright 2015-2019, Institute for Systems Biology # # Licensed under the", "from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "project_id: project number of the BQ data project (typically isb-cgc's project number) #", "23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id:", "# # Unless required by applicable law or agreed to in writing, software", "express or implied. # See the License for the specific language governing permissions", "type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type)", "load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array", "range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output", "CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True)", "file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj", "code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr',", "chromosome_array = [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance,", "either express or implied. # See the License for the specific language governing", "2015-2019, Institute for Systems Biology # # Licensed under the Apache License, Version", "\"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id,", "provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query) # project_id: project number of", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "from io import StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import", "chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id,", "help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type:", "the License. # You may obtain a copy of the License at #", "[str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider", "number) # data_type: 4-letter data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type',", "include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows,", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type)", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class", "total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry:", "= 0 # Poll for completion while all_done is False and total_retries <", "file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for", "config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array =", "retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict =", "standard_library standard_library.install_aliases() from builtins import str from builtins import range from csv import", "provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run) if", "include_header=False): fieldnames = [x['name'] for x in schema] file_obj = StringIO() writer =", "config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for c in range(1,", "with the License. # You may obtain a copy of the License at", "open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue()) @click.command() @click.argument('data_type', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str,", "type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array):", "= chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result =", "= provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count = 0 # Poll", "{done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time) logging.debug(\"Done: {done} retry: {retry}\".format(done=str(all_done), retry=total_retries)) query_result", "import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper", "for the specific language governing permissions and # limitations under the License. ###", "Poll for completion while all_done is False and total_retries < poll_retry_limit: poll_count +=", "django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference", "from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"isb_cgc.settings\") import django django.setup() import click", "completion while all_done is False and total_retries < poll_retry_limit: poll_count += 1 total_retries", "law or agreed to in writing, software # distributed under the License is", "= provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time = provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries =", "the License for the specific language governing permissions and # limitations under the", "poll_count += 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done = is_finished sleep(poll_sleep_time)", "{retry}\".format(done=str(all_done), retry=total_retries)) query_result = provider.download_and_unpack_query_result() return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "from builtins import str from builtins import range from csv import DictWriter from", "(required for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature", "all_done = False total_retries = 0 poll_count = 0 # Poll for completion", "= StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def", "@click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def", "if config_json is not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type)", "in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query = provider.build_query(config_instance) print(query)", "@click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type", "eg. GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\",", "GNAB @click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str,", "in schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows)", "run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class =", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class =", "config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider =", "str from builtins import range from csv import DictWriter from json import load", "writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows, schema,", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "# Copyright 2015-2019, Institute for Systems Biology # # Licensed under the Apache", "project number) # data_type: 4-letter data type code, eg. GNAB @click.command() @click.argument('project_id', type=click.INT)", "return query_result def load_config_from_path(config_class, config_json_path): config_dict = load_json(open(config_json_path, 'r')) return config_class.from_dict(config_dict) def get_csv_object(data_rows,", "load as load_json import logging from io import StringIO from time import sleep", "See the License for the specific language governing permissions and # limitations under", "is not None: config_instance = load_config_from_path(config_class, config_json) else: config_dict = FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "c in range(1, 23)] chromosome_array.extend(['X', 'Y']) else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "logging.basicConfig(level=logging.INFO) def run_query(project_id, provider, config): job_reference = provider.submit_query_and_get_job_ref(project_id) poll_retry_limit = provider.BQ_JOB_POLL_MAX_RETRIES poll_sleep_time =", "FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_type(feature_type) config_instance = config_class.from_dict(config_dict) if not chromosome_array: chromosome_array = [str(c) for c in", "provider.BQ_JOB_POLL_SLEEP_TIME all_done = False total_retries = 0 poll_count = 0 # Poll for", "import logging from io import StringIO from time import sleep import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\",", "csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run) if __name__ == '__main__': main()", "import django django.setup() import click from bq_data_access.v2.feature_id_utils import FeatureDataTypeHelper logging.basicConfig(level=logging.INFO) def run_query(project_id, provider,", "run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run)", "StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader() writer.writerows(data_rows) return file_obj def save_csv(data_rows,", "and total_retries < poll_retry_limit: poll_count += 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id)", "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", "type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is not None:", "type=str, multiple=True, help=\"Chromosome (required for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type", "total_retries = 0 poll_count = 0 # Poll for completion while all_done is", "total_retries < poll_retry_limit: poll_count += 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done", "get_csv_object(data_rows, schema, include_header=False): fieldnames = [x['name'] for x in schema] file_obj = StringIO()", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "for methylation)\") def run(project_id, data_type, csv_path, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type:", "permissions and # limitations under the License. ### from __future__ import print_function from", "provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main(): pass main.add_command(print_query) main.add_command(run) if __name__ == '__main__':", "provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider,", "x in schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header: writer.writeheader()", "FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature type: {}\".format(str(feature_type))) config_class = FeatureDataTypeHelper.get_feature_def_config_from_data_type(feature_type) provider_class = FeatureDataTypeHelper.get_feature_def_provider_from_data_type(feature_type) if config_json is", "file_obj def save_csv(data_rows, schema, csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path,", "multiple=True, help=\"Chromosome (required for methylation)\") def print_query(data_type, config_json, chromosome_array): feature_type = FeatureDataTypeHelper.get_type(data_type) logging.info(\"Feature", "(typically isb-cgc's project number) # data_type: 4-letter data type code, eg. GNAB @click.command()", "for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array) query =", "{}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group() def main():", "else: chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance)))", "< poll_retry_limit: poll_count += 1 total_retries += 1 is_finished = provider.is_bigquery_job_finished(project_id) all_done =", "import range from csv import DictWriter from json import load as load_json import", "csv_path, include_header=False): file_obj = get_csv_object(data_rows, schema, include_header=include_header) with open(csv_path, 'w') as file_handle: file_handle.write(file_obj.getvalue())", "@click.command() @click.argument('project_id', type=click.INT) @click.argument('data_type', type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True,", "for x in schema] file_obj = StringIO() writer = DictWriter(file_obj, fieldnames=fieldnames) if include_header:", "{}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result = run_query(project_id, provider, config_instance) save_csv(result, provider.get_mysql_schema(), csv_path, include_header=True) @click.group()", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "schema, include_header=False): fieldnames = [x['name'] for x in schema] file_obj = StringIO() writer", "chromosome_array = chromosome_array[0].split(\",\") provider = provider_class(config_instance, chromosome_array=chromosome_array) logging.info(\"Output CSV: {}\".format(csv_path)) logging.info(\"Config: {}\".format(str(config_instance))) result", "for Systems Biology # # Licensed under the Apache License, Version 2.0 (the", "0 poll_count = 0 # Poll for completion while all_done is False and", "type=str) @click.argument('csv_path', type=str) @click.option('--config_json', type=str) @click.option('-chr', \"chromosome_array\", type=str, multiple=True, help=\"Chromosome (required for methylation)\")", "Biology # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "= [str(c) for c in range(1, 23)] chromosome_array.extend(['X', 'Y']) provider = provider_class(config_instance, chromosome_array=chromosome_array)" ]
[ "W, bs) x = x.view(N, C // (self.bs ** 2), H * self.bs,", "kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps", "keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None: u_x =", "u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None: u_x = self.pool(u_x)", "torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def", "as nn import torch.nn.functional as F from torchvision.models import resnet18 as _resnet18 from", "= [l[0] for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64,", "torchvision.models import resnet34 as _resnet34 from torchvision.models import resnet50 as _resnet50 __all__ =", "math import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models", "self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True),", "forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if", "feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs) def resnet50(**kwargs):", "C // (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H,", "self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), #", "* u_x), inplace=True) out = x / torch.sqrt(v_x + self.eps) return out class", "if name == 'resnet18': return _resnet18 elif name == 'resnet34': return _resnet34 elif", "_resnet18 elif name == 'resnet34': return _resnet34 elif name == 'resnet50': return _resnet50", "1), ) def _get_backbone(self, name): if name == 'resnet18': return _resnet18 elif name", "dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None: u_x", "C//bs^2, H * bs, W * bs) return x class ResnetCGD(nn.Module): ''' '''", "else: raise ValueError('Not supported backbone') def forward(self, x): ''' ''' # color layer", "u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x), inplace=True) out =", "nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1,", "class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x): N,", "name): if name == 'resnet18': return _resnet18 elif name == 'resnet34': return _resnet34", "H * bs, W * bs) return x class ResnetCGD(nn.Module): ''' ''' def", "stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1),", "bs) return x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' '''", "nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer =", "fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34',", "resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs) def resnet50(**kwargs): return ResnetCGD(backbone='resnet50',", "_resnet18 from torchvision.models import resnet34 as _resnet34 from torchvision.models import resnet50 as _resnet50", "nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1),", "self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()] self.color_layer =", "2), H * self.bs, W * self.bs) # (N, C//bs^2, H * bs,", "''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1", "stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3,", "dim=1, keepdim=True) if self.pool is not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2)", "deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4'])", "base layers base_layers = {} for n, layer in zip(self.base_names, self.base_layers): x =", "nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps = eps def forward(self, x):", "* bs) return x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): '''", "def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True)", "= nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # )", "self.base_names = [l[0] for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3,", "x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd", "torch.nn as nn import torch.nn.functional as F from torchvision.models import resnet18 as _resnet18", "eps def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1,", "self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name): if name", "# color layer color_feat = self.color_layer(x) # base layers base_layers = {} for", "x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs)", ") self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name): if", "def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size", "elif name == 'resnet34': return _resnet34 elif name == 'resnet50': return _resnet50 else:", "// (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H, W)", "zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x # grad layer grad_feat =", "_get_backbone(self, name): if name == 'resnet18': return _resnet18 elif name == 'resnet34': return", "self.color_layer(x) # base layers base_layers = {} for n, layer in zip(self.base_names, self.base_layers):", "NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1),", ") # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1,", "keepdim=True) if self.pool is not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x", "if kernel_size[0] > 1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding)", "''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l", "# NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1,", "x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool", "torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module):", "torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None:", "self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu", "import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def", "self.bs, W * self.bs) # (N, C//bs^2, H * bs, W * bs)", "self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()] self.color_layer = nn.Sequential(", "= self.color_layer(x) # base layers base_layers = {} for n, layer in zip(self.base_names,", "bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer", "self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x), inplace=True) out", "stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2,", "nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name): if name == 'resnet18': return", "ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained)", "feature layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) #", "from torchvision.models import resnet34 as _resnet34 from torchvision.models import resnet50 as _resnet50 __all__", "block_size def forward(self, x): N, C, H, W = x.size() x = x.view(N,", "# nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer =", "W) # (N, bs, bs, C//bs^2, H, W) x = x.permute(0, 3, 4,", "1, 1), ) def _get_backbone(self, name): if name == 'resnet18': return _resnet18 elif", "self.bs = block_size def forward(self, x): N, C, H, W = x.size() x", "stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential( #", "from torchvision.models import resnet18 as _resnet18 from torchvision.models import resnet34 as _resnet34 from", "/ torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs", "2), H, W) # (N, bs, bs, C//bs^2, H, W) x = x.permute(0,", "= x.size() x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H,", "else: self.pool = None self.eps = eps def forward(self, x): u_x = torch.mean(x,", "layer(x) base_layers[n] = x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature", "1, padding) else: self.pool = None self.eps = eps def forward(self, x): u_x", "(u_x * u_x), inplace=True) out = x / torch.sqrt(v_x + self.eps) return out", "x): ''' ''' # color layer color_feat = self.color_layer(x) # base layers base_layers", "(N, C//bs^2, H * bs, W * bs) return x class ResnetCGD(nn.Module): '''", "l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),", "import math import torch import torch.nn as nn import torch.nn.functional as F from", "padding) else: self.pool = None self.eps = eps def forward(self, x): u_x =", "1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name):", "__init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names", "deep_feat = torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1)", "['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): '''", "= self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()] self.color_layer", "resnet18 as _resnet18 from torchvision.models import resnet34 as _resnet34 from torchvision.models import resnet50", "= F.relu(u_x2 - (u_x * u_x), inplace=True) out = x / torch.sqrt(v_x +", "(self.bs ** 2), H * self.bs, W * self.bs) # (N, C//bs^2, H", "(self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H, W) x", "bs) x = x.view(N, C // (self.bs ** 2), H * self.bs, W", "4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs) x =", "for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1,", "'resnet50': return _resnet50 else: raise ValueError('Not supported backbone') def forward(self, x): ''' '''", "None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x *", "# self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1),", "layer color_feat = self.color_layer(x) # base layers base_layers = {} for n, layer", "NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def", "fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat,", "self.pool = None self.eps = eps def forward(self, x): u_x = torch.mean(x, dim=1,", "fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1)", "5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs) x = x.view(N, C", "2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2,", "return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs) def resnet50(**kwargs): return ResnetCGD(backbone='resnet50', **kwargs)", "def forward(self, x): ''' ''' # color layer color_feat = self.color_layer(x) # base", "kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0),", "kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size,", "x = x.view(N, C // (self.bs ** 2), H * self.bs, W *", "torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat", "layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm", "[l[0] for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3,", "= None self.eps = eps def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True)", "# (N, C//bs^2, H, bs, W, bs) x = x.view(N, C // (self.bs", "self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x), inplace=True) out = x /", "super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in", "== 'resnet34': return _resnet34 elif name == 'resnet50': return _resnet50 else: raise ValueError('Not", "= self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm,", "nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer", "= nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2),", "__init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x): N, C, H, W", "def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x): N, C, H,", "# deep_feat = torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu],", "1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs) x = x.view(N,", "color_feat = self.color_layer(x) # base layers base_layers = {} for n, layer in", "def _get_backbone(self, name): if name == 'resnet18': return _resnet18 elif name == 'resnet34':", "1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self,", "DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), )", "== 'resnet18': return _resnet18 elif name == 'resnet34': return _resnet34 elif name ==", "# base layers base_layers = {} for n, layer in zip(self.base_names, self.base_layers): x", "forward(self, x): N, C, H, W = x.size() x = x.view(N, self.bs, self.bs,", "self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu],", "name == 'resnet34': return _resnet34 elif name == 'resnet50': return _resnet50 else: raise", "out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x):", "* self.bs, W * self.bs) # (N, C//bs^2, H * bs, W *", "= x / torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size):", "int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1] > 1:", "for n, layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x #", "torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs =", "= nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4,", "grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs):", "kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1] > 1: self.pool", "import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models import", "self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm,", "64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2,", "1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps = eps", "H * self.bs, W * self.bs) # (N, C//bs^2, H * bs, W", "= torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is not", "DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self, x): N, C,", "import torch.nn as nn import torch.nn.functional as F from torchvision.models import resnet18 as", "forward(self, x): ''' ''' # color layer color_feat = self.color_layer(x) # base layers", "fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs):", "x = layer(x) base_layers[n] = x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) #", "C, H, W = x.size() x = x.view(N, self.bs, self.bs, C // (self.bs", "dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs): return", "= nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name): if name ==", "_resnet34 elif name == 'resnet50': return _resnet50 else: raise ValueError('Not supported backbone') def", "elif name == 'resnet50': return _resnet50 else: raise ValueError('Not supported backbone') def forward(self,", "resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self,", "''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers =", "nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1,", "''' # color layer color_feat = self.color_layer(x) # base layers base_layers = {}", "import resnet18 as _resnet18 from torchvision.models import resnet34 as _resnet34 from torchvision.models import", "// (self.bs ** 2), H * self.bs, W * self.bs) # (N, C//bs^2,", "= self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x), inplace=True)", "H, W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2,", "nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2),", "1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer", "'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if", "return _resnet34 elif name == 'resnet50': return _resnet50 else: raise ValueError('Not supported backbone')", "x.size() x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W)", "nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1), ) def _get_backbone(self, name): if name == 'resnet18':", "0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if", "= nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps = eps def forward(self,", "= block_size def forward(self, x): N, C, H, W = x.size() x =", "> 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps =", "layers base_layers = {} for n, layer in zip(self.base_names, self.base_layers): x = layer(x)", "self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def", "NormLayer(3, 1, 1), ) def _get_backbone(self, name): if name == 'resnet18': return _resnet18", "1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), #", "'resnet34': return _resnet34 elif name == 'resnet50': return _resnet50 else: raise ValueError('Not supported", "<gh_stars>0 import math import torch import torch.nn as nn import torch.nn.functional as F", "padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size)", "u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x, dim=1, keepdim=True) if self.pool is", "'resnet18': return _resnet18 elif name == 'resnet34': return _resnet34 elif name == 'resnet50':", "or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None", "v_x = F.relu(u_x2 - (u_x * u_x), inplace=True) out = x / torch.sqrt(v_x", "nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3,", "# (N, bs, bs, C//bs^2, H, W) x = x.permute(0, 3, 4, 1,", "1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool =", "self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2,", "raise ValueError('Not supported backbone') def forward(self, x): ''' ''' # color layer color_feat", "''' ''' # color layer color_feat = self.color_layer(x) # base layers base_layers =", ") self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0),", "super().__init__() self.bs = block_size def forward(self, x): N, C, H, W = x.size()", "import torch.nn.functional as F from torchvision.models import resnet18 as _resnet18 from torchvision.models import", ") self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential(", "def forward(self, x): N, C, H, W = x.size() x = x.view(N, self.bs,", "in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x # grad layer grad_feat", "bs, W, bs) x = x.view(N, C // (self.bs ** 2), H *", "nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer =", ") def _get_backbone(self, name): if name == 'resnet18': return _resnet18 elif name ==", "W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H,", "= torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return", "= (kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1] > 1: self.pool =", "= torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None: u_x = self.pool(u_x) u_x2", "# nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True),", "from torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class", "** 2), H, W) # (N, bs, bs, C//bs^2, H, W) x =", "W * bs) return x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False):", "nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2),", "torch.nn.functional as F from torchvision.models import resnet18 as _resnet18 from torchvision.models import resnet34", "(kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size,", "inplace=True) out = x / torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def", "name == 'resnet18': return _resnet18 elif name == 'resnet34': return _resnet34 elif name", "= self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat,", "3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs) x", "1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3,", "torch import torch.nn as nn import torch.nn.functional as F from torchvision.models import resnet18", "padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), )", "is not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 -", "nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer", "feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18',", "self.base_layers): x = layer(x) base_layers[n] = x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1'])", "fm, fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return", "# ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer =", "bs, W * bs) return x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18',", "pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0]", "kernel_size) if kernel_size[0] > 1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1,", "= layer(x) base_layers[n] = x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep", "torchvision.models import resnet18 as _resnet18 from torchvision.models import resnet34 as _resnet34 from torchvision.models", "''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] >", "bs, bs, C//bs^2, H, W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous()", "torch.mean(x*x, dim=1, keepdim=True) if self.pool is not None: u_x = self.pool(u_x) u_x2 =", "- (u_x * u_x), inplace=True) out = x / torch.sqrt(v_x + self.eps) return", "backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names =", "color layer color_feat = self.color_layer(x) # base layers base_layers = {} for n,", "import resnet34 as _resnet34 from torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD',", "F from torchvision.models import resnet18 as _resnet18 from torchvision.models import resnet34 as _resnet34", "1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2,", "def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2])", "dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs)", "as _resnet18 from torchvision.models import resnet34 as _resnet34 from torchvision.models import resnet50 as", "# deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu =", "= nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) #", "backbone') def forward(self, x): ''' ''' # color layer color_feat = self.color_layer(x) #", "self.eps = eps def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 =", "nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2,", "u_x), inplace=True) out = x / torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module):", "nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3, 1, 1), # ) self.upsample_layer = nn.Sequential(", "** 2), H * self.bs, W * self.bs) # (N, C//bs^2, H *", "nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True),", "> 1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool", "NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2),", "ValueError('Not supported backbone') def forward(self, x): ''' ''' # color layer color_feat =", "2, padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), #", "NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int):", "(N, bs, bs, C//bs^2, H, W) x = x.permute(0, 3, 4, 1, 5,", "net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True),", "kernel_size[0] > 1 or kernel_size[1] > 1: self.pool = nn.AvgPool2d(kernel_size, 1, padding) else:", "x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net", "base_layers = {} for n, layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n]", "self.bs, C // (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2,", "in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4), nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64),", "base_layers[n] = x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer", "grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd = self.downsample_layer(base_layers['layer2'])", "def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs) def resnet50(**kwargs): return", "H, W) # (N, bs, bs, C//bs^2, H, W) x = x.permute(0, 3,", "fm, fu], dim=1) feat = torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def", "= x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W,", "super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1 or", "as F from torchvision.models import resnet18 as _resnet18 from torchvision.models import resnet34 as", "return _resnet50 else: raise ValueError('Not supported backbone') def forward(self, x): ''' ''' #", "= self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3'])", "supported backbone') def forward(self, x): ''' ''' # color layer color_feat = self.color_layer(x)", "layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x # grad layer", "block_size): super().__init__() self.bs = block_size def forward(self, x): N, C, H, W =", "F.relu(u_x2 - (u_x * u_x), inplace=True) out = x / torch.sqrt(v_x + self.eps)", "u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x),", "padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True), # nn.MaxPool2d(2, stride=2), # NormLayer(3,", "* self.bs) # (N, C//bs^2, H * bs, W * bs) return x", "isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1] >", "= torch.cat([color_feat, grad_feat, fm, fu], dim=1) return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs)", "eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0]", "= x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) # (N,", "= eps def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2 = torch.mean(x*x,", "self.bs) # (N, C//bs^2, H * bs, W * bs) return x class", "C//bs^2, H, W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N,", "return x class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__()", "# fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat =", "NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential( # nn.ReLU(inplace=True),", "2).contiguous() # (N, C//bs^2, H, bs, W, bs) x = x.view(N, C //", "return _resnet18 elif name == 'resnet34': return _resnet34 elif name == 'resnet50': return", "if self.pool is not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x =", "not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2 - (u_x", "N, C, H, W = x.size() x = x.view(N, self.bs, self.bs, C //", "= nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3,", "= ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06):", "x): N, C, H, W = x.size() x = x.view(N, self.bs, self.bs, C", "padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2,", "if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) if kernel_size[0] > 1 or kernel_size[1]", "+ self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size", "return feat def resnet18(**kwargs): return ResnetCGD(backbone='resnet18', **kwargs) def resnet34(**kwargs): return ResnetCGD(backbone='resnet34', **kwargs) def", "'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__()", "layer # fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat", "self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), )", "_resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0,", "nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), ) self.mid_layer = nn.Sequential( nn.ReLU(inplace=True), NormLayer(3, 1, 1),", "= x.view(N, C // (self.bs ** 2), H * self.bs, W * self.bs)", "None self.eps = eps def forward(self, x): u_x = torch.mean(x, dim=1, keepdim=True) u_x2", "{} for n, layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x", "W * self.bs) # (N, C//bs^2, H * bs, W * bs) return", "self.pool is not None: u_x = self.pool(u_x) u_x2 = self.pool(u_x2) v_x = F.relu(u_x2", "= self.pool(u_x2) v_x = F.relu(u_x2 - (u_x * u_x), inplace=True) out = x", "(N, C//bs^2, H, bs, W, bs) x = x.view(N, C // (self.bs **", "''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for", "__all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0),", "as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size,", "''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers", "x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs,", "# (N, C//bs^2, H * bs, W * bs) return x class ResnetCGD(nn.Module):", "nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential(", "return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__() self.bs = block_size def forward(self,", "_resnet34 from torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34', 'resnet50']", "'resnet18', 'resnet34', 'resnet50'] class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' '''", "x.view(N, C // (self.bs ** 2), H * self.bs, W * self.bs) #", "self.pool = nn.AvgPool2d(kernel_size, 1, padding) else: self.pool = None self.eps = eps def", "x / torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def __init__(self, block_size): super().__init__()", "_resnet50 else: raise ValueError('Not supported backbone') def forward(self, x): ''' ''' # color", "grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd = self.downsample_layer(base_layers['layer2']) fm =", "self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1) feat =", "= self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd, fm, fu], dim=1) feat", "out = x / torch.sqrt(v_x + self.eps) return out class DepthToSpace(nn.Module): def __init__(self,", "self.bs, self.bs, C // (self.bs ** 2), H, W) # (N, bs, bs,", "resnet34 as _resnet34 from torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18',", "n, layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] = x # grad", "= x # grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer #", "1), nn.AvgPool2d(2, 2, padding=0), ) self.grad_norm_layer = nn.Sequential( nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), NormLayer(3, 1,", "nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()] self.color_layer = nn.Sequential( nn.AvgPool2d(4, stride=4),", "W = x.size() x = x.view(N, self.bs, self.bs, C // (self.bs ** 2),", "= {} for n, layer in zip(self.base_names, self.base_layers): x = layer(x) base_layers[n] =", "H, W = x.size() x = x.view(N, self.bs, self.bs, C // (self.bs **", "C//bs^2, H, bs, W, bs) x = x.view(N, C // (self.bs ** 2),", "as _resnet34 from torchvision.models import resnet50 as _resnet50 __all__ = ['ResnetCGD', 'resnet18', 'resnet34',", "x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) #", "# grad layer grad_feat = self.grad_norm_layer(base_layers['layer1']) # deep feature layer # fd =", "* bs, W * bs) return x class ResnetCGD(nn.Module): ''' ''' def __init__(self,", "nn import torch.nn.functional as F from torchvision.models import resnet18 as _resnet18 from torchvision.models", "name == 'resnet50': return _resnet50 else: raise ValueError('Not supported backbone') def forward(self, x):", "C // (self.bs ** 2), H * self.bs, W * self.bs) # (N,", "1, 1), # ) self.upsample_layer = nn.Sequential( nn.ReLU(inplace=True), DepthToSpace(2), NormLayer(3, 1, 1), )", "nn.MaxPool2d(2, stride=2), NormLayer(3, 1, 1), nn.AvgPool2d(2, 2, padding=0), ) # self.downsample_layer = nn.Sequential(", "class ResnetCGD(nn.Module): ''' ''' def __init__(self, backbone='resnet18', pretrained=False): ''' ''' super().__init__() net =", "bs, C//bs^2, H, W) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() #", "x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) # (N, bs,", "__init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size, int): kernel_size =", "H, bs, W, bs) x = x.view(N, C // (self.bs ** 2), H", "fd = self.downsample_layer(base_layers['layer2']) fm = self.mid_layer(base_layers['layer3']) fu = self.upsample_layer(base_layers['layer4']) # deep_feat = torch.cat([fd,", "class NormLayer(nn.Module): def __init__(self, kernel_size, padding=(0, 0), eps=1e-06): ''' ''' super().__init__() if isinstance(kernel_size,", "net = self._get_backbone(backbone)(pretrained=pretrained) self.base_layers = nn.ModuleList(list(net.children())[:-2]) self.base_names = [l[0] for l in net.named_children()]", "== 'resnet50': return _resnet50 else: raise ValueError('Not supported backbone') def forward(self, x): '''" ]
[ "if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban]", "import json import settings class ABNClient: mutations = None new_last_transaction = None FILENAME", "settings class ABNClient: mutations = None new_last_transaction = None FILENAME = \"last_transactions.json\" def", "new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp >", "with open(self.FILENAME, 'r') as f: data = json.load(f) return data except FileNotFoundError: return", "self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def", "last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp =", "FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp()", "import settings class ABNClient: mutations = None new_last_transaction = None FILENAME = \"last_transactions.json\"", "as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data", "mutations) def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction", "> new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction", "mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp", "for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction =", "result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in", "mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp", "> last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w')", "json import settings class ABNClient: mutations = None new_last_transaction = None FILENAME =", "transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME,", "def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with", "return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self):", "mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result = []", "= int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp:", "self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban,", "= None new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT)", "= abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban)", "return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban,", "self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0))", "self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions,", "try: with open(self.FILENAME, 'r') as f: data = json.load(f) return data except FileNotFoundError:", "new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return", "with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r')", "json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data = json.load(f)", "0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction", "import abna import json import settings class ABNClient: mutations = None new_last_transaction =", "new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def", "= int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp'])", "\"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self,", "last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as", "new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result", "abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return", "get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data = json.load(f) return data except", "self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations =", "def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data = json.load(f) return data", "iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for", "abna import json import settings class ABNClient: mutations = None new_last_transaction = None", "new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD)", "ABNClient: mutations = None new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self): self.sess", "int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if", "transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp >", "= transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def", "get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0", "= None FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions", "= [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']:", "result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f:", "None FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions =", "= self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp", "self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp =", "in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if", "def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban):", "iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result =", "mutations = None new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self): self.sess =", "0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp", "settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations)", "transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] =", "f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data =", "save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME,", "= new_last_transaction return result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f)", "def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations):", "def get_only_new_mutations(self, iban, mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction =", "transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self):", "__init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations", "= self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self,", "None new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER,", "int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction: new_last_transaction = transaction_timestamp if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation'])", "f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f: data = json.load(f) return", "result def save_last_transaction_timestamp(self): with open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try:", "= \"last_transactions.json\" def __init__(self): self.sess = abna.Session(settings.ABNA_ACCOUNT) self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def", "'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as f:", "get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban, mutations) def get_only_new_mutations(self, iban, mutations): result", "= 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp = int(mutation['mutation']['transactionTimestamp']) if transaction_timestamp > new_last_transaction:", "if transaction_timestamp > last_transaction_timestamp: result.append(mutation['mutation']) self.last_transactions[iban] = new_last_transaction return result def save_last_transaction_timestamp(self): with", "self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD) self.last_transactions = self.get_last_transaction_timestamp() def get_mutations(self, iban): mutations = self.sess.mutations(iban) return self.get_only_new_mutations(iban,", "open(self.FILENAME, 'w') as f: json.dump(self.last_transactions, f) def get_last_transaction_timestamp(self): try: with open(self.FILENAME, 'r') as", "[] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation in mutations['mutationsList']['mutations']: transaction_timestamp", "open(self.FILENAME, 'r') as f: data = json.load(f) return data except FileNotFoundError: return {}", "mutations): result = [] last_transaction_timestamp = int(self.last_transactions.get(iban, 0)) new_last_transaction = 0 for mutation", "class ABNClient: mutations = None new_last_transaction = None FILENAME = \"last_transactions.json\" def __init__(self):" ]
[ "inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid +", "list[int]) -> list[TreeNode]: if not preorder or not inorder: return None root =", "None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid +", "inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) return root", "self.val = val self.left = left self.right = right class Solution: def buildTree(self,", "self.right = right class Solution: def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]:", "return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid", "mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right =", "not preorder or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0])", "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:", "+ 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :])", "list[int], inorder: list[int]) -> list[TreeNode]: if not preorder or not inorder: return None", "preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not preorder or not inorder: return", "list[TreeNode]: if not preorder or not inorder: return None root = TreeNode(preorder[0]) mid", "self.left = left self.right = right class Solution: def buildTree(self, preorder: list[int], inorder:", "left self.right = right class Solution: def buildTree(self, preorder: list[int], inorder: list[int]) ->", "def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not preorder or not", "preorder or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left", "= right class Solution: def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if", "= inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid", "right class Solution: def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not", "buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not preorder or not inorder:", "= TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid])", ": mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid +", "inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 :", "-> list[TreeNode]: if not preorder or not inorder: return None root = TreeNode(preorder[0])", "val self.left = left self.right = right class Solution: def buildTree(self, preorder: list[int],", "mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1", "not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1", "= self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :],", "1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) return", "class Solution: def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not preorder", "if not preorder or not inorder: return None root = TreeNode(preorder[0]) mid =", "or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left =", "root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1", "right=None): self.val = val self.left = left self.right = right class Solution: def", "TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right", "inorder: list[int]) -> list[TreeNode]: if not preorder or not inorder: return None root", "self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1 :], inorder[mid", "= val self.left = left self.right = right class Solution: def buildTree(self, preorder:", "__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right", "Solution: def buildTree(self, preorder: list[int], inorder: list[int]) -> list[TreeNode]: if not preorder or", "= left self.right = right class Solution: def buildTree(self, preorder: list[int], inorder: list[int])", "TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) root.right", "root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : mid + 1]," ]
[ "= Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome)", "return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__': p", "nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar())", "def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade = idade self.filhos =list(filhos)", "return f'{cls}, {olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome)", "f'{cls}, {olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade)", "class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome", "= nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def", "def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return", "= idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42", "42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__': p =", "{olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome", "idade=None): self.nome = nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá'", "if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome =", "2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade = idade self.filhos", "print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome) print(p.idade) print(Pessoa.olhos) print(p.__dict__) print(Pessoa.metodo_estatico())", "'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if", "cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls},", "*filhos, nome=None, idade=None): self.nome = nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self):", "metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__':", "return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}'", "def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p))", "<gh_stars>0 class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.nome =", "== '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade", "idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod", "print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome) print(p.idade) print(Pessoa.olhos) print(p.__dict__) print(Pessoa.metodo_estatico()) print(Pessoa.nome_e_atributos_de_classe())", "print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome) print(p.idade) print(Pessoa.olhos) print(p.__dict__)", "Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade", "@classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ == '__main__': p = Pessoa(nome='Mariane')", "Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome) print(p.idade)", "print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35 print(p.nome) print(p.idade) print(Pessoa.olhos)", "self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def", "self.nome = nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod", "olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade =", "def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__ ==", "nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico():", "self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return", "'__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade =", "nome=None, idade=None): self.nome = nome self.idade = idade self.filhos =list(filhos) def cumprimentar(self): return", "=list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls):", "p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas' p.idade = 35", "@staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls}, {olhos}' if __name__", "__name__ == '__main__': p = Pessoa(nome='Mariane') print(Pessoa.cumprimentar(p)) print(p.cumprimentar()) print(p.nome) print(p.idade) p.nome = 'Douglas'", "= 2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade = idade", "__init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade = idade self.filhos =list(filhos) def" ]
[]
[ "WHERE table_schema = '%s' AND table_name = '%s' AND column_name = '%s';\" \\", "with open(destination, 'w') as f: f.write(response.read()) return destination #/* ======================================================================= */# #/* Define", "@staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define main() function #/*", "Hostname for the target database [default: localhost] --db-user Username used for database connection", "----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a NULL value \"\"\"", "arg) # This catches three conditions: # 1. The last argument is a", "field_map_order: query_fields = [] query_values = [] # If the report already exists,", "THE # SOFTWARE. # # =================================================================================== # \"\"\" Scraper for the \"temporary\" NRC", "returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method", "'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to", "0 arg_error = False while i < len(args): try: arg = args[i] #", "are intended to return a final value to be inserted into the target", "'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } },", "query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ',", "target schema, 'sheet_name': Name of source sheet in input file, 'column': Name of", "file will be downloaded to If used in conjunction with --no-download it is", "of help related flags :return: 1 for exit code purposes :rtype: int \"\"\"", "try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) #", ":type row: :param map_def: :type map_def: :rtype: :return: \"\"\" # TODO: Use 24", "timestamp from XLRD reading a date encoded field :type stamp: float :param workbook_datemode:", "query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #", "without restriction, including without limitation the rights to use, copy, modify, merge, publish,", "None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */#", "are treated as primary keys and drive processing. Rather than process the input", "Make sure schema and table exist in the DB query = \"SELECT *", "= True print(\"ERROR: Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) #", "arg == '--no-execute-queries': i += 1 execute_queries = False # Additional options elif", "file :type destination: str|unicode :param overwrite: specify whether or not an existing destination", "map definitions are declared to describe which fields in which sheets should be", "----------------------------------------------------------------------- */# #/* Cleanup and final return #/* ----------------------------------------------------------------------- */# # Update user", "elif arg == '--file-to-process': i += 2 file_to_process = abspath(args[i - 1]) #", "only reads rows from the sheet specified in the field map and NOT", "to permit persons to whom the Software is # furnished to do so,", "be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes around", "arg_error = True print(\"ERROR: Invalid argument: %s\" % arg) # This catches three", "======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see if a report has already", "{ 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table':", "'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS',", "map example below states that whatever value is in sheet 'CALLS' and column", "the normal sheet cache, but with a list of rows instead of a", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, {", "'0.1-dev' __release__ = 'August 8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__", "timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod", "use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "a single field map to process for map_def in field_map[db_map]: # Don't need", "for exit code purposes :rtype: int \"\"\" print(\"\"\" %s version %s - released", "print(\"ERROR: Need write permission for download directory: %s\" % dirname(file_to_process)) # Handle subsample", "% (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* -----------------------------------------------------------------------", "`whoami` --db-host localhost \"\"\" from __future__ import division from __future__ import print_function from", "exit code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state',", "on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/*", "usage information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Usage:", "row was extracted as described in the field map sheet_seqnos_field The field in", "queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/* ======================================================================= */# #/* Define", "properly iterate the 'i' variable except IndexError: i += 1 arg_error = True", "file, 'column': Name of source column in sheet_name, 'processing': { # Optional -", "* FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s' AND column_name", "not properly iterate the 'i' variable except IndexError: i += 1 arg_error =", "to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid()", "'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field':", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "print (\"Error printing SQL query to console (unicode weirdness?\") print (e.message) if execute_queries:", "{row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError: # Sheet was empty pass", "all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id =", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing':", "= True print(\"ERROR: Can't find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column']))", "#/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination,", "if sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname]", "to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these", "a final value to be inserted into the target field described in the", "schema_table: str|unicode :return: number of rows in the specified schema.table :rtype: int \"\"\"", "> 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process", "initial query above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)]", "= kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace this", "process for map_def in field_map[db_map]: # Don't need to process the reportnum information", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted", "function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method", "to deal in the Software without restriction, including without limitation the rights to", "to the processing function in order to get a result else: value =", "ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert", "'db_schema': Name of target schema, 'sheet_name': Name of source sheet in input file,", "in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if necessary if", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing':", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"',", "function in order to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook,", "nothing left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static", "KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\" % value) #", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "NULL values - these should be handled elsewhere so this is more of", "Arguments, parameters, flags, options, etc. --version Version and ownership information --license License information", "db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR: Invalid DB", "field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace this hack with", "'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table':", "*/# # Execute query, but not if the report already exists query =", "----------------------------------------------------------------------- */# bail = False # Make sure arguments were properly parse if", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "report already exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode,", "software and associated documentation files (the \"Software\"), to deal # in the Software", "should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator", "= kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value =", "map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping ...\") for", "reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum')", "the value from the sheet and add to the query if row is", "'Another Row 1 Val', 'Column3': 'Even More Row 1 Values' }, { 'Column1':", "map: The field map below shows that the value in the 'RESPONSIBLE_COMPANY' column", "mistyping of 'IN' 'YARDS': 3 } # Database is expecting to handle the", "queries immediately before execution Automatically turns off the progress indicator --no-execute-queries Don't execute", "and to permit persons to whom the Software is # furnished to do", "open(destination, 'w') as f: f.write(response.read()) return destination #/* ======================================================================= */# #/* Define name_current_file()", "'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\",", "in the field map but this behavior is not required. If the function", "row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return output #/* -----------------------------------------------------------------------", "containing reportnums as keys and rows as values row The current row being", "be one map for every field in a table. The structure for field", "and this permission notice shall be included in all copies or substantial portions", "======================================================================= */# #/* Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL", "unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* -----------------------------------------------------------------------", "{ 'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84,", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all", "overwrite the default credentials and settings if db_connection_string is None: db_connection_string = \"host='%s'", "find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get", "COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* =======================================================================", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema':", "xlrd.Sheet :return: list of elements, each containing one row of the sheet as", "} }, :param args: arguments from the commandline (sys.argv[1:] in order to drop", "Maximum width for this field - used in string slicing 'db_schema': Name of", "indent = \" \" * 2 print(\"Initial row counts:\") for schema_table, count in", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude',", "to download the input file --no-download Don't download the input file --overwrite-download If", "None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent to a different table", "--db-connection-string Explicitly define a Postgres supported connection string. All other --db-* options are", "int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs):", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"',", "*/# @staticmethod def blockid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value',", ":rtype: :return: \"\"\" # TODO: Use 24 hour time workbook = kwargs['workbook'] row", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success -", "Found a matching row if row[sheet_seqnos_field] == uid: # The first instance goes", "in ('--help', '-help', '--h', '-h'): return print_help() elif arg in ('--usage', '-usage'): return", "of rows instead of a dictionary containing reportnums as keys and rows as", "to any person obtaining a copy # of this software and associated documentation", "list of help related flags :return: 1 for exit code purposes :rtype: int", "maps = { 'table_name': [ { 'db_table': Name of target table, 'db_field': Name", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, {", "print_help() function #/* ======================================================================= */# def print_help(): \"\"\" Detailed help information :return: 1", "num_ids)) sys.stdout.flush() # Get field maps for one table for db_map in field_map_order:", "args[i - 1] # Commandline print-outs elif arg == '--no-print-progress': i += 1", "= args[i - 1] elif arg == '--db-host': i += 2 db_host =", "sheet: xlrd.Sheet :return: list of elements, each containing one row of the sheet", "URL to download from :type url: str|unicode :param destination: target path and filename", "without any additional processing. Note the quotes around the table name. { 'db_table':", "----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot()", "Note the quotes around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width':", "2 print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table", "workbook object The callable object specified in map_def['processing']['function'] is responsible for ALL queries.", "necessary information to the processing function in order to get a result else:", "1 #/* ======================================================================= */# #/* Define print_license() function #/* ======================================================================= */# def print_license():", "#/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet do", "be handled by the parent process so this value is # returned at", "target field. There should be one map for every field in a table.", "'YARDS': 3 } # Database is expecting to handle the normalization by reading", "# # # The MIT License (MIT) # # Copyright (c) 2014 SkyTruth", "'LONG_QUAD' } } }, { # TODO: Implement - check notes about which", "rows in the specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM", "None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER',", "set of field map definitions are declared to describe which fields in which", "= kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing']", "above copyright notice and this permission notice shall be included in all copies", "more of a safety net if value is None or not value: value", "this utility --usage Arguments, parameters, flags, options, etc. --version Version and ownership information", "is not required. If the function itself handles all queries internally it can", "SEQNOS/reportnum's are gathered from one of the workbook's sheets. The default column in", "'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name':", "sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements, each containing", "and final return #/* ----------------------------------------------------------------------- */# # Update user padding = max([len(i) for", "function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float", "#/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO:", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs):", "#/* ----------------------------------------------------------------------- */# #/* Cache initial DB row counts for final stat printing", "print(\"ERROR: An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/*", "sheet and row by row, a set of field map definitions are declared", "table - specified in the field map arguments for e_db_map in extras_field_maps: for", "else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get", "'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table':", "workbook = kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/*", "'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES':", "elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file = True elif arg ==", "copies of the Software, and to permit persons to whom the Software is", "'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3 } # Database", "minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower() not", "for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'],", "'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments from the", "just like a csv.DictReader row sheet The entire sheet from which the row", "exit code purposes :rtype: int \"\"\" print(__license__) return 1 #/* ======================================================================= */# #/*", "target field described in the field map but this behavior is not required.", "- 1] elif arg == '--db-name': i += 2 db_name = args[i -", "----------------------------------------------------------------------- */# #/* Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False", "obtaining a copy # of this software and associated documentation files (the \"Software\"),", "None if not used 'function': Callable object responsible for additional sub-processing 'args': {", "but can be specified by the user. This set of ID's are treated", "None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def", "Automatically turns off the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \"", "reportnums as keys and rows as values row The current row being processed", "arg_error = False while i < len(args): try: arg = args[i] # Help", "have a report_exists method on each of the field map classes so we", "definition in the set of mappings for map_def in field_map[db_map]: # Attempt to", "of operations for a given ID is as follows: 1. Get an ID", "primary keys for uid in unique_report_ids: # Update user uid_i += 1 if", "'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */#", "1 Values' }, { 'Column1': 'Row 2 Val', 'Column2': 'Another Row 2 Val',", "single quotes in the string causes problems on insert because the entire #", "file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True", "same general logic. \"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min =", "----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache all sheets needed", "# Handle NULL values - these should be handled elsewhere so this is", "contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output #/*", "except (ValueError, KeyError): output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define", "minutes :type minutes: int :param seconds: coordinate seconds :type seconds: int :param quadrant:", "'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema':", "Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing':", "the bare minimum field map example below states that whatever value is in", "0 #/* ======================================================================= */# #/* Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp,", "% file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download from", "validate_field_map_error = True print(\"ERROR: Can't find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'],", "= dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */#", "True elif arg == '--subsample': i += 2 process_subsample = args[i - 1]", "Make sure the value is properly quoted if value not in (None, '',", "1 print_queries = True print_progress = False elif arg == '--no-execute-queries': i +=", "%s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if", "1 #/* ======================================================================= */# #/* Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees,", "insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define", "'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name':", "@staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static", "Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, { 'db_table': Name of", "map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: # UID doesn't appear", "======================================================================= */# #/* Define main() function #/* ======================================================================= */# def main(args): \"\"\" Main", "'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "== '--print-queries': i += 1 print_queries = True print_progress = False elif arg", ":param degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes :type minutes:", "'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public',", "successfully parse arguments\") # Make sure the downloaded file is not going to", "populate a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with", "timestamp to a Postgres supported timestamp format. This method eliminates repitition :param workbook:", "kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries']", "if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field", "code purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help More detailed description of", "----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\"", "Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see if", "user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids))", "in ('s', 'w'): output *= -1 return output #/* ======================================================================= */# #/* Define", "but the user did not supply the parameter # 2. The arg parser", "sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError: # Sheet was", "for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None #", "for field maps is roughly as follows: All field maps = { 'table_name':", "NULL value value = db_null_value # Pass all necessary information to the processing", "'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args':", "if value is None or not value: value = db_null_value # Assemble query", "a timestamp to a Postgres supported timestamp format. This method eliminates repitition :param", "'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } },", "= kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try:", "'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public',", "Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/* =======================================================================", "'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "elif arg == '--subsample-min': i += 2 process_subsample_min = args[i - 1] #", "value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific values", "Name of target table, 'db_field': Name of target field, 'db_field_width': Maximum width for", "materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\"", "== '--file-to-process': i += 2 file_to_process = abspath(args[i - 1]) # Database connection", "sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object", "*/# #/* Cleanup and final return #/* ----------------------------------------------------------------------- */# # Update user padding", "to overwrite the default credentials and settings if db_connection_string is None: db_connection_string =", "Val', 'Column3': 'Even more Row 3 Values' } ] :param sheet: XLRD sheet", "kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode']", "----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define", "'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "======================================================================= */# #/* Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d", "Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in the", "database user [default: ''] --download-url URL from which to download the input file", "if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input", "return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class", "of 'IN' 'YARDS': 3 } # Database is expecting to handle the normalization", "'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None },", "in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime()", "- 1] elif arg == '--db-pass': i += 2 db_pass = args[i -", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error =", "= [] extra_query_values = [] # Found a matching row if row[sheet_seqnos_field] ==", "subsample if necessary if process_subsample is not None and process_subsample < len(unique_report_ids): #", "#/* ----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */# # Loops: # Get", "'function': NrcScrapedMaterialFields.st_id } } ] } } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"':", "rows instead of a dictionary containing reportnums as keys and rows as values", "workbook XLRD workbook object The callable object specified in map_def['processing']['function'] is responsible for", "'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table':", "an XLRD sheet object into a list of rows, each structured as a", "the download, this flag is not needed due the default file name containing", "get the sheet to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does", "quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals = (None, '', u'')", "The field map below shows that the value in the 'RESPONSIBLE_COMPANY' column in", "above copyright notice and this permission notice shall be included in all #", "'\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, {", "exists, in the target table, skip everything else _schema, _table = db_map.split('.') if", "'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area',", "number 1234 is being processed, the bare minimum field map example below states", "of field map definitions are declared to describe which fields in which sheets", "information must be passed to the NrcParsedReportFields.longitude() function where the actual processing happens.", "db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value", "'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } },", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static method #/* -----------------------------------------------------------------------", "id's unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys():", "in the field map # This query must be handled by the parent", "Invalid argument i += 1 arg_error = True print(\"ERROR: Invalid argument: %s\" %", "db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map definitions #/* -----------------------------------------------------------------------", "specified in the field map and NOT the extra field maps # specified", "reportnum=uid, schema=_schema, table=_table): # Get a single field map to process for map_def", "cursor to be used for all queries db_null_value Value to use for NULL", "= None process_subsample_min = 0 # User feedback settings print_progress = True print_queries", "'%s' AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results", "and process_subsample < len(unique_report_ids): # TODO: Delete constraining line - needed to verify", "e: print(\"ERROR: Could not download from URL: %s\" % download_url) print(\" URLLIB Error:", "= [] # If the report already exists, in the target table, skip", "#/* Adjust options #/* ----------------------------------------------------------------------- */# # Database - must be done here", "2 db_user = args[i - 1] elif arg == '--db-name': i += 2", "query 4. Execute the insert statement 5. Repeat steps 2-4 until all tables", "None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE',", "a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map,", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "class is used as a namespace to provide better organization and to prevent", "table specified in the field map # This query must be handled by", "insert because the entire # value is single quoted value = value.replace(\"'\", '\"')", "function #/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download a file :param", ":param workbook: :type workbook: :param row: :type row: :param map_def: :type map_def: :rtype:", "extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\" % value) # int|float value", "=================================================================================== # \"\"\" Scraper for the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py", "isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite, destination)) # Download", "is being processed, the bare minimum field map example below states that whatever", "*/# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for permanent archival :param", "% (indent, schema_table + ' ' * (padding - len(schema_table) + 4), count))", "of the Software, and to permit persons to whom the Software is #", "required. If the function itself handles all queries internally it can return '__NO_QUERY__'", "input_name: str|unicode :return: output formatted name :rtype: str|unicode \"\"\" dt = datetime.now() dt", "insert statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name':", "= False download_file = True process_subsample = None process_subsample_min = 0 # User", "help information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help:", "Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\" \"Row 3", "num_ids = len(unique_report_ids) uid_i = 0 # Loop through the primary keys for", "goes from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is", "Main routine to parse, transform, and insert Current.xlsx into the tables used by", "datetime down to the second. --file-to-process Specify where the input file will be", "\"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */#", "query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields),", "query = \"SELECT * FROM information_schema.columns WHERE table_schema = '%s' AND table_name =", "being processed - structured just like a csv.DictReader row sheet The entire sheet", "Need write permission for download directory: %s\" % dirname(file_to_process)) # Handle subsample if", "======================================================================= */# #/* Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds,", "'db_field': Name of target field, 'db_field_width': Maximum width for this field - used", "'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name':", "*/# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields()", "including without limitation the rights # to use, copy, modify, merge, publish, distribute,", "None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER',", "#/* ----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */# # Database - must", "db_host = 'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode", "isinstance(value, unicode): # Having single quotes in the string causes problems on insert", "not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file straight into", "*/# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/*", "# If the value is not a float, change it to nothing so", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\"", "minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to decimal degrees :param", "*= -1 return output #/* ======================================================================= */# #/* Define column_names() function #/* =======================================================================", "'\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid", "'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public',", "causes problems on insert because the entire # value is single quoted value", "name) :type args: list :return: 0 on success and 1 on error :rtype:", "3. Process all field maps and assemble an insert query 4. Execute the", "\"\"\" Several methods require converting a timestamp to a Postgres supported timestamp format.", "since it was added to the initial query above if map_def['db_field'] == db_seqnos_field:", "map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error = True", "... } } }, { 'db_table': Name of target table, 'db_field': Name of", "in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + '", "command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__ import division", "value = '' # No sheen size - nothing to do if value", "the Software is # furnished to do so, subject to the following conditions:", "reading a date encoded field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type", "\"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define", "db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail = False", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "*/# #/* Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): #", "'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } },", "properly parse if arg_error: bail = True print(\"ERROR: Did not successfully parse arguments\")", "initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent to a different table -", "specified sheet - populate a NULL value value = db_null_value # Pass all", "= kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode =", "1 #/* ======================================================================= */# #/* Define print_version() function #/* ======================================================================= */# def print_version():", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"':", "in illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value:", "%s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field maps for one table for", "print_help_info() elif arg in ('--help', '-help', '--h', '-h'): return print_help() elif arg in", "#/* Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\"", "download, this flag is not needed due the default file name containing datetime", "Val', 'Column3': 'Even more Row 2 Values' } { 'Column1': 'Row 3 Val',", "%s - released %s \"\"\" % (__docname__, __version__, __release__)) return 1 #/* =======================================================================", "*/# @staticmethod def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries']", "file --overwrite-download If the --file-to-process already exists and --no-download has not been specified,", "@staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function called in the return statement", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name',", "database. These fields require an additional processing step that is highly specific and", "that the specified file already exists and should be used for processing [default:", "change it to nothing so the next test fails try: value = float(value)", "1] elif arg == '--db-pass': i += 2 db_pass = args[i - 1]", "*/# #/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\"", "*/# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing':", "on insert because the entire # value is single quoted value = value.replace(\"'\",", "+ 4), count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent,", "BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* -----------------------------------------------------------------------", "purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1}", "Additional options elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file = True elif", "a float, change it to nothing so the next test fails try: value", "sys.stdout.flush() # Get field maps for one table for db_map in field_map_order: query_fields", "#/* ----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD workbook for processing #/*", "Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing':", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None },", "process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid", "# This document is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # #", "described in the field map but this behavior is not required. If the", "information necessary to execute one of these processing functions. A class is used", "'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } },", "ID's are treated as primary keys and drive processing. Rather than process the", "import os from os.path import * import sys import urllib2 import psycopg2 import", "Structured similar to the normal sheet cache, but with a list of rows", "xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name']) #", "'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table':", "be passed to the NrcParsedReportFields.longitude() function where the actual processing happens. Field maps", "Explicitly define a Postgres supported connection string. All other --db-* options are ignored.", "'db_table': Name of target table, 'db_field': Name of target field, 'db_field_width': Maximum width", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': {", "of that but must still supply the expected post-normalization format if unit.upper() not", "XLRD workbook for processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB:", ":param map_def: :type map_def: :rtype: :return: \"\"\" # TODO: Use 24 hour time", "quadrant to decimal degrees :param degrees: coordinate degrees :type degrees: int :param minutes:", "*/# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date a", "True print(\"ERROR: Can't find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) #", "tables have been processed Example bare minimum field map: The field map below", "*/# #/* Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return", "'Even more Row 3 Values' } ] :param sheet: XLRD sheet object from", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "seconds: int :param quadrant: coordinate quadrant (N, E, S, W) :type quadrant: str|unicode", "from the commandline (sys.argv[1:] in order to drop the script name) :type args:", "one target table 3. Process all field maps and assemble an insert query", "which means that if ID number 1234 is being processed, the bare minimum", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "'Row 1 Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even More Row 1", "2 download_url = args[i - 1] elif arg == '--file-to-process': i += 2", "settings print_progress = True print_queries = False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"',", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row = kwargs['row'] map_def = kwargs['map_def']", "in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding - len(schema_table)", "'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id',", "to whom the Software is furnished to do so, subject to the following", "sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function", "[--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress]", "is not None and map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if", "1 Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More", "----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs)", "*/# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/*", "print_version(): \"\"\" Print script version information :return: 1 for exit code purposes :rtype:", "datetime import getpass import os from os.path import * import sys import urllib2", "'Column2': 'Another Row 3 Val', 'Column3': 'Even more Row 3 Values' } ]", "int \"\"\" print(\"\"\" %s version %s - released %s \"\"\" % (__docname__, __version__,", "'', u'') for iv in illegal_vals: if iv in (degrees, minutes, seconds, quadrant):", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */#", "'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field':", "\"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method #/* -----------------------------------------------------------------------", "+= 1 execute_queries = False # Additional options elif arg == '--overwrite-download': i", "*/# #/* Prep DB connection and XLRD workbook for processing #/* ----------------------------------------------------------------------- */#", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "The more complicated field map states that a specific function must do more", "by reading from a field containing \"1.23 METERS\" # This function takes care", "'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS',", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water',", "'\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid", "'--subsample': i += 2 process_subsample = args[i - 1] elif arg == '--subsample-min':", "used in string slicing 'db_schema': Name of target schema, 'sheet_name': Name of source", "Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__ import", "is not needed due the default file name containing datetime down to the", "a NULL value value = db_null_value # Pass all necessary information to the", "'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"',", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "arg == '--download-url': i += 2 download_url = args[i - 1] elif arg", "queries. The processing functions are intended to return a final value to be", "cache, but with a list of rows instead of a dictionary containing reportnums", "connect to database: %s\" % db_connection_string) print(\" Postgres Error: %s\" % e) return", "= basename(__file__) __license__ = ''' The MIT License (MIT) Copyright (c) 2014 SkyTruth", "having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY',", "len(__docname__))) return 1 #/* ======================================================================= */# #/* Define print_license() function #/* ======================================================================= */#", "unicode(multipliers[unit.upper()] * value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static", "'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip',", "OR OTHER DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage()", "is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error", "#/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod", "the DB query = \"SELECT * FROM information_schema.columns WHERE table_schema = '%s' AND", "but not if the report already exists query = \"\"\"%s %s (%s) VALUES", "Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The", "file :param url: URL to download from :type url: str|unicode :param destination: target", "try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds']", "'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': {", "'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime }", "Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of SEQNOS/reportnum's are gathered", "u'') for iv in illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise", "additional arguments and information necessary to execute one of these processing functions. A", "'-' * len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/* Define print_help_info() function", "value == 'INC': value = 'INCIDENT' return value #/* ======================================================================= */# #/* Define", "field mapping ...\") for db_map in field_map_order: # Check each field definition in", "initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/*", "import getpass import os from os.path import * import sys import urllib2 import", "= [db_seqnos_field] query_values = [str(uid)] else: # Get the row for this sheet", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "{ 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name':", "'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, {", "not successfully parse arguments\") # Make sure the downloaded file is not going", "is # furnished to do so, subject to the following conditions: # #", "first instance goes into the table specified in the field map # This", "Prep DB connection and XLRD workbook for processing #/* ----------------------------------------------------------------------- */# # Test", "sheet_cache = kwargs['sheet_cache'] # TODO: This currently only reads rows from the sheet", "#/* ======================================================================= */# #/* Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\"", "called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static", "'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function called in the", "db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific values if isinstance(value, str) or", "names :rtype: list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */#", "field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache", "'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema':", "row of the sheet as a dictionary :rtype: dict \"\"\" output = []", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "\".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception as e: print", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "+= 1 download_file = False elif arg == '--download-url': i += 2 download_url", "specified in the processing args. Currently not a problem since # Build query", "'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI':", "4), count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table", "----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define", "that no specific column contains the value required for public.\"NrcParsedReport\".longitude Instead, some information", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function':", "can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that a", "= kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field =", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # ===================================================================================", "SOFTWARE. # # =================================================================================== # \"\"\" Scraper for the \"temporary\" NRC incident spreadsheet", "Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "'' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field =", "row for row in sheet_dict} except IndexError: # Sheet was empty pass #", "for this field - used in string slicing 'db_schema': Name of target schema,", "} ], } The order of operations for a given ID is as", "ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table +", "'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { # TODO: Implement - check notes", "process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i = 0 # Loop through", "output Current.xlsx name for permanent archival :param input_name: input file name (e.g. Current.xlsx)", "verify everything was wroking unique_report_ids = [i for i in unique_report_ids if i", "db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "each ID which means that if ID number 1234 is being processed, the", "= kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define", "a problem since # Build query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]:", "for one target table 3. Process all field maps and assemble an insert", "'\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status,", "kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value", "'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", ":type url: str|unicode :param destination: target path and filename for downloaded file :type", "'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name':", "[ { 'db_table': Name of target table, 'db_field': Name of target field, 'db_schema':", "for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']],", "Use 24 hour time workbook = kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def']", "dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */# #/*", "'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field", "'\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, {", "'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name':", "*/# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" %", "import unicode_literals from datetime import datetime import getpass import os from os.path import", "to prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */#", "% map_def['sheet_name']) # Make sure schema and table exist in the DB query", "- populate a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value", "final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table, count in", "value is properly quoted if value not in (None, '', u'', db_null_value): if", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ], } #/* -----------------------------------------------------------------------", "%s\" % process_subsample) # Exit if any problems were encountered if bail: return", "= '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The MIT", "queries should be printed as they are executed raw_sheet_cache Structured similar to the", "def print_version(): \"\"\" Print script version information :return: 1 for exit code purposes", ":return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table']", "Several converters require \"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value']", "\"\"\" print(__license__) return 1 #/* ======================================================================= */# #/* Define print_help() function #/* =======================================================================", "to see if a report has already been submitted to a table :param", "notice shall be included in all # copies or substantial portions of the", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table':", "hour time workbook = kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']],", "--file-to-process Specify where the input file will be downloaded to If used in", "query_fields.append(map_def['db_field']) # Only put quotes around specific values if isinstance(value, str) or isinstance(value,", "catches three conditions: # 1. The last argument is a flag that requires", "# Database connection elif arg == '--db-connection-string': i += 2 db_connection_string = args[i", "(db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */#", "the sheet to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not", "in the specified sheet - populate a NULL value value = db_null_value #/*", "# This processing function handled ALL inserts - tell parent process there's nothing", "print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing function handled ALL inserts -", "TODO: Implement - check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field':", "current user] --db-name Name of target database [default: skytruth] --db-pass Password for database", "and map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "the NrcParsedReportFields.longitude() function where the actual processing happens. Field maps using additional processing", "= \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ',", "len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts and destroy", "----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/* -----------------------------------------------------------------------", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table':", "'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name':", "'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None },", "# TODO: This currently only reads rows from the sheet specified in the", "% (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\"", "if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name,", "each containing one row of the sheet as a dictionary :rtype: dict \"\"\"", "download directory: %s\" % dirname(file_to_process)) # Handle subsample if process_subsample is not None:", "'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { #", "'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with all options:", "[formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function #/*", "< len(unique_report_ids): # TODO: Delete constraining line - needed to verify everything was", "connection elif arg == '--db-connection-string': i += 2 db_connection_string = args[i - 1]", "% process_subsample) # Exit if any problems were encountered if bail: return 1", "float, change it to nothing so the next test fails try: value =", "The reportnum field in the database db_write_mode The first part of the SQL", "'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, {", "the output Current.xlsx name for permanent archival :param input_name: input file name (e.g.", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "= [] query_values = [] # If the report already exists, in the", "# Establish a DB connection and turn on dict reading db_conn = psycopg2.connect(db_connection_string)", "Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"':", "'\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, {", "} }, ], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */#", "\"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, {", "set of field maps for a single table to process # Get a", "+ 4), count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts", "return output #/* ======================================================================= */# #/* Define report_exists() function #/* ======================================================================= */# def", "code purposes :rtype: int \"\"\" print(__license__) return 1 #/* ======================================================================= */# #/* Define", "printed as they are executed raw_sheet_cache Structured similar to the normal sheet cache,", "processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to the processing function", "Adjust options #/* ----------------------------------------------------------------------- */# # Database - must be done here in", "%s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the sheet", "if map_def['sheet_name'] is not None and map_def['column'] is not None: try: sheet =", "path and filename for downloaded file :type destination: str|unicode :param overwrite: specify whether", "*/# #/* Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating", "into the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations,", "= 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' #", "os.W_OK): bail = True print(\"ERROR: Need write permission for download directory: %s\" %", "Could not connect to database: %s\" % db_connection_string) print(\" Postgres Error: %s\" %", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing':", "timestamp format. This method eliminates repitition :param workbook: :type workbook: :param row: :type", "} }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name']) # Make sure schema and", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS',", "query above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else:", "print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table +", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table':", "basename(__file__) __license__ = ''' The MIT License (MIT) Copyright (c) 2014 SkyTruth Permission", "#/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "related flags :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help", "name :rtype: str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.')", "'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema':", "not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]:", "*/# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */#", "from the insert statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema':", "class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly", "ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/*", "to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a", "{ 'function': BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults", "for every field in a table. The structure for field maps is roughly", "the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a", "to parse, transform, and insert Current.xlsx into the tables used by the Alerts", "value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/*", "field in a table. The structure for field maps is roughly as follows:", "= os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample", "Row 3 Val', 'Column3': 'Even more Row 3 Values' } ] :param sheet:", "print(\"\"\" %s version %s - released %s \"\"\" % (__docname__, __version__, __release__)) return", "1] elif arg == '--file-to-process': i += 2 file_to_process = abspath(args[i - 1])", "kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg],", "'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' }", "print(\"\"\" Help flags: --help More detailed description of this utility --usage Arguments, parameters,", "the very end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences", "#/* Define main() function #/* ======================================================================= */# def main(args): \"\"\" Main routine to", "%s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB connection", "#/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/*", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. '''", "} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "[default: current user] --db-name Name of target database [default: skytruth] --db-pass Password for", "%s\" % dirname(file_to_process)) # Handle subsample if process_subsample is not None: try: process_subsample", "to decimal degrees :param degrees: coordinate degrees :type degrees: int :param minutes: coordinate", "#/* ======================================================================= */# __version__ = '0.1-dev' __release__ = 'August 8, 2014' __author__ =", "Get a set of field maps for a single table to process #", "('--license', '-usage'): return print_license() # Spreadsheet I/O elif arg == '--no-download': i +=", "2 db_host = args[i - 1] elif arg == '--db-user': i += 2", "'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None },", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values -", "target table, skip everything else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid,", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to the processing function in order", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\" % (schema,", "Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement", "if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" %", "+= 2 file_to_process = abspath(args[i - 1]) # Database connection elif arg ==", "__release__ = 'August 8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ =", "latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* -----------------------------------------------------------------------", "} } }, { 'db_table': Name of target table, 'db_field': Name of target", "field map with all options: This field map shows that no specific column", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "parameters but the user did not supply the parameter # 2. The arg", "and add to the query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "@staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static method", "# Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, ], 'TABLE_NAME': [", "'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else: #", "Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map =", ":rtype: int \"\"\" print(\"\"\" Help flags: --help More detailed description of this utility", "and ownership information --license License information \"\"\") return 1 #/* ======================================================================= */# #/*", "'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "[ { 'Column1': 'Row 1 Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even", "as e: print(\"ERROR: Could not connect to database: %s\" % db_connection_string) print(\" Postgres", "process there's nothing left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define", "def column_names(sheet, formatter=str): \"\"\" Get the ordered column names from an XLRD sheet", "def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to decimal", "grouped by table and center around the target field. There should be one", "input file name (e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted name :rtype:", "date a Postgres supported timestamp :param stamp: timestamp from XLRD reading a date", "the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these should", "# Handle subsample if process_subsample is not None: try: process_subsample = int(process_subsample) process_subsample_min", "'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } }", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "arg_error = True print(\"ERROR: An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/*", "Software, and to permit persons to whom the Software is furnished to do", "functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static method", "data #/* ----------------------------------------------------------------------- */# # Loops: # Get a report number to process", "'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype',", "Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type", "= psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not connect to database:", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name", "accidentally deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR:", "@staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs)", "to a table :param seqnos: reportnum :type seqnos: int|float :param field: :type field:", "query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields),", "=================================================================================== # # # The MIT License (MIT) # # Copyright (c) 2014", "spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" %", "from the sheet and add to the query if row is not None:", "======================================================================= */# #/* Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\"", "- released %s \"\"\" % (__docname__, __version__, __release__)) return 1 #/* ======================================================================= */#", "in the database db_write_mode The first part of the SQL statement for writes", "'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments from the commandline (sys.argv[1:] in", "highly specific and cannot be re-used. The field map definition contains all of", "NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly to", "NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "More Row 1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row 2", "contains the value required for public.\"NrcParsedReport\".longitude Instead, some information must be passed to", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema':", "of the additional arguments and information necessary to execute one of these processing", "for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' *", ":type args: list :return: 0 on success and 1 on error :rtype: int", "in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC',", "(None, '', u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\",", "'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The MIT License (MIT) Copyright (c)", "%s\" % download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e:", "passed to the NrcParsedReportFields.longitude() function where the actual processing happens. Field maps using", "Add this field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle", "*/# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required", "target table 3. Process all field maps and assemble an insert query 4.", "======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into a list", "'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "----------------------------------------------------------------------- */# #/* Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs):", "# Database db_connection_string = None db_host = 'localhost' db_name = 'skytruth' db_user =", "== '': return db_null_value # Found a sheen size and unit - perform", "-1 return output #/* ======================================================================= */# #/* Define column_names() function #/* ======================================================================= */#", "no specific column contains the value required for public.\"NrcParsedReport\".longitude Instead, some information must", "'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public',", "sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd()", "a report has already been submitted to a table :param seqnos: reportnum :type", "%s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the user has write permission to", "other --db-* options are ignored. --db-host Hostname for the target database [default: localhost]", "a list of rows instead of a dictionary containing reportnums as keys and", "= kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value = row[map_def['column']]", ":param url: URL to download from :type url: str|unicode :param destination: target path", "script name) :type args: list :return: 0 on success and 1 on error", "= True print(\"ERROR: Need write permission for download directory: %s\" % dirname(file_to_process)) #", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } }, {", "USE OR OTHER DEALINGS IN THE # SOFTWARE. # # =================================================================================== # \"\"\"", "----------------------------------------------------------------------- */# # Update user padding = max([len(i) for i in field_map.keys()]) indent", "\"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']]", "except psycopg2.OperationalError as e: print(\"ERROR: Could not connect to database: %s\" % db_connection_string)", "Field maps using additional processing always receive the following kwargs: all_field_maps All field", "- these should be handled elsewhere so this is more of a safety", "mapping ...\") for db_map in field_map_order: # Check each field definition in the", "ValueError: bail = True print(\"ERROR: Invalid subsample or subsample min - must be", "post-normalization format if unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value)", "db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/*", "*/# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if", "# This query must be handled by the parent process so this value", "Name of target database [default: skytruth] --db-pass Password for database user [default: '']", "field described in the field map but this behavior is not required. If", "======================================================================= */# #/* Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination, overwrite=False):", "#/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "elif arg == '--db-connection-string': i += 2 db_connection_string = args[i - 1] elif", "consume all parameters for an argument # 3. The arg parser did not", "file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file", "here in order to allow the user to overwrite the default credentials and", "'August 8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__", "True print(\"ERROR: Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make", "*/# #/* Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return", "Handle subsample if process_subsample is not None: try: process_subsample = int(process_subsample) process_subsample_min =", "#!/usr/bin/env python # This document is part of scraper # https://github.com/SkyTruth/scraper # ===================================================================================", "if process_subsample is not None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except", "sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to the insert statement", "ValueError: value = '' # No sheen size - nothing to do if", "'--file-to-process': i += 2 file_to_process = abspath(args[i - 1]) # Database connection elif", "initial_db_row_counts[schema_table])) # Success - commit inserts and destroy DB connections # db_conn.commit() #", "'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': {", "', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp',", "permission notice shall be included in all # copies or substantial portions of", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } }, { #", "Positional arguments and errors else: # Invalid argument i += 1 arg_error =", "arg == '--subsample': i += 2 process_subsample = args[i - 1] elif arg", "re-used. The field map definition contains all of the additional arguments and information", "= kwargs['row'] value = row[map_def['column']] if value == 'INC': value = 'INCIDENT' return", "} #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string", "Get an ID 2. Get a set of field maps for one target", "TODO: This currently only reads rows from the sheet specified in the field", "Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None)", "XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements, each", "more complicated field map states that a specific function must do more of", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "define a Postgres supported connection string. All other --db-* options are ignored. --db-host", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [", "__version__ = '0.1-dev' __release__ = 'August 8, 2014' __author__ = '<NAME>' __source__ =", "settings if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host,", "in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/*", "be downloaded to If used in conjunction with --no-download it is assumed that", "} } } ], } The order of operations for a given ID", "__future__ import division from __future__ import print_function from __future__ import unicode_literals from datetime", "Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/*", "\" * len(__docname__))) return 1 #/* ======================================================================= */# #/* Define print_license() function #/*", "or not an existing destination should be overwritten :type overwrite: bool :return: path", "2 process_subsample_min = args[i - 1] # Positional arguments and errors else: #", "= '%s' AND table_name = '%s' AND column_name = '%s';\" \\ % (map_def['db_schema'],", "user. This set of ID's are treated as primary keys and drive processing.", "'Column2': 'Another Row 2 Val', 'Column3': 'Even more Row 2 Values' } {", "#/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into a", "(db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating the field map", "elif arg == '--no-print-progress': i += 1 print_progress = False elif arg ==", "'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS',", "column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states", "Current.xlsx) :type input_name: str|unicode :return: output formatted name :rtype: str|unicode \"\"\" dt =", "Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres", "2 Values' } { 'Column1': 'Row 3 Val', 'Column2': 'Another Row 3 Val',", "} } ], } The order of operations for a given ID is", "problem since # Build query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields", "specified, blindly overwrite the file. Unless the user is specifying a specific target", "arg == '--db-host': i += 2 db_host = args[i - 1] elif arg", "ignored. --db-host Hostname for the target database [default: localhost] --db-user Username used for", "*/# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function called in the return", "- check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema':", "+ \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field maps for one", "'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant':", "as dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache = {} for sname", "+= 1 overwrite_downloaded_file = True elif arg == '--subsample': i += 2 process_subsample", "'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static method #/* ----------------------------------------------------------------------- */#", "column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "process_subsample is not None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError:", "{1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres supported connection string. All", "DB connection and XLRD workbook for processing #/* ----------------------------------------------------------------------- */# # Test connection", "the file. Unless the user is specifying a specific target for the download,", "# TODO: Use 24 hour time workbook = kwargs['workbook'] row = kwargs['row'] map_def", "#/* Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\"", "one map for every field in a table. The structure for field maps", "default file name containing datetime down to the second. --file-to-process Specify where the", "is specifying a specific target for the download, this flag is not needed", "a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps,", "all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "#/* Define print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\" Command line usage", "= kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] #", "dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* =======================================================================", "matching row if row[sheet_seqnos_field] == uid: # The first instance goes into the", "sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache", "# User feedback settings print_progress = True print_queries = False execute_queries = True", "= {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems():", "raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output = int(degrees) + int(minutes) /", "see if a report has already been submitted to a table :param seqnos:", "\"\"\" Several converters require \"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value =", "else: multipliers = { 'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES':", "map but this behavior is not required. If the function itself handles all", "'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] } } } }, { 'db_table':", "value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object):", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "= kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache =", "#/* Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO:", "all field maps and assemble an insert query 4. Execute the insert statement", "if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent to", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } } ], } The order", "'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"',", "@staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* -----------------------------------------------------------------------", "# returned at the very end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']]", "----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string = None", "- 1]) # Database connection elif arg == '--db-connection-string': i += 2 db_connection_string", "the reportnum uid The current SEQNOS/reportnum being processed workbook XLRD workbook object The", "be accidentally deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail = True", "#/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds,", "... } } }, ], 'TABLE_NAME': [ { 'db_table': Name of target table,", "sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/*", "download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could", "#/* Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE'", "db_null_value): if isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single", "order to drop the script name) :type args: list :return: 0 on success", "0 #/* ======================================================================= */# #/* Commandline Execution #/* ======================================================================= */# if __name__ ==", "ordered column names from an XLRD sheet object :param sheet: XLRD sheet object", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ],", "initial DB row counts for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts =", "that whatever value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "str) or isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single quotes cause problems", "= datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split)", "copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None", "raw_sheet_cache = {} for sname in workbook.sheet_names(): if sname not in sheet_cache: try:", "not a problem since # Build query initial_value_to_be_returned = None for row in", "a different table - specified in the field map arguments for e_db_map in", "#/* Define print_help() function #/* ======================================================================= */# def print_help(): \"\"\" Detailed help information", "for r in range(1, sheet.nrows): # Skip first row since it contains the", "sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't", "which sheets should be inserted into which table in which schema. Each field", "{ # TODO: Implement - check notes about which column to use 'db_table':", "'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode = 'INSERT", "def download(url, destination, overwrite=False): \"\"\" Download a file :param url: URL to download", "column_names(sheet, formatter=str): \"\"\" Get the ordered column names from an XLRD sheet object", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "sheen size - nothing to do if value == '' or unit ==", "} } ] } } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema':", "1 print_progress = False elif arg == '--print-queries': i += 1 print_queries =", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location',", "if row[sheet_seqnos_field] == uid: # The first instance goes into the table specified", "1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084,", "'-version'): return print_version() elif arg in ('--license', '-usage'): return print_license() # Spreadsheet I/O", "to console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done processing -", "of the field map classes so we don't have to # have the", "#/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See", "True print_progress = False elif arg == '--no-execute-queries': i += 1 execute_queries =", "ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static method #/*", "NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public',", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH',", "DB row counts for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts:", "(degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower()", "db_connection_string) print(\" Postgres Error: %s\" % e) return 1 #/* ----------------------------------------------------------------------- */# #/*", "KeyError: row = None # If no additional processing is required, simply grab", "(\"Error printing SQL query to console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query)", "which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "======================================================================= */# def print_license(): \"\"\" Print out license information :return: 1 for exit", "range = xrange #/* ======================================================================= */# #/* Build information #/* ======================================================================= */# __version__", "operations for a given ID is as follows: 1. Get an ID 2.", "This set of ID's are treated as primary keys and drive processing. Rather", "all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add", "download_url) print(\" URLLIB Error: %s\" % e) return 1 # Prep workbook print(\"Opening", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing':", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field':", "first part of the SQL statement for writes (e.g. INSERT INTO) execute_queries Specifies", "field maps and assemble an insert query 4. Execute the insert statement 5.", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "behavior is not required. If the function itself handles all queries internally it", "= 'INCIDENT' return value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/* =======================================================================", "@staticmethod def blockid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None)", "being inserted into Postgres timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode))", "str|unicode :return: number of rows in the specified schema.table :rtype: int \"\"\" query", "'processing': None }, Example field map with all options: This field map shows", "% (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating the field", "options #/* ----------------------------------------------------------------------- */# # Database - must be done here in order", "#/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "so this value is # returned at the very end if initial_value_to_be_returned is", "map_def: :type map_def: :rtype: :return: \"\"\" # TODO: Use 24 hour time workbook", "% (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if", "'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping", "#/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD", "''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR:", "copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED", "= args[i - 1] # Positional arguments and errors else: # Invalid argument", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file", "connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not connect to", "__author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The", "NrcParsedReportFields.longitude() function where the actual processing happens. Field maps using additional processing always", "target database [default: skytruth] --db-pass Password for database user [default: ''] --download-url URL", "'processing': { 'function': BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */# #/* Define", "counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' '", "Make sure the downloaded file is not going to be accidentally deleted if", "latitude() and longitude() methods require the same general logic. \"\"\" try: row =", "Permission is hereby granted, free of charge, to any person obtaining a copy", "Prep workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: #", "map is applied against each ID which means that if ID number 1234", "be re-used. The field map definition contains all of the additional arguments and", "map_def['processing']['function'] is responsible for ALL queries. The processing functions are intended to return", "be included in all copies or substantial portions of the Software. THE SOFTWARE", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "should be set to None if not used 'function': Callable object responsible for", "whom the Software is furnished to do so, subject to the following conditions:", "minutes: int :param seconds: coordinate seconds :type seconds: int :param quadrant: coordinate quadrant", "Update user padding = max([len(i) for i in field_map.keys()]) indent = \" \"", "*/# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def = kwargs['map_def'] row", "any problems were encountered if bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep", "# ALL occurrences are sent to a different table - specified in the", "/ 3600 if quadrant.lower() in ('s', 'w'): output *= -1 return output #/*", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } }, {", "like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static method #/* -----------------------------------------------------------------------", "import urllib2 import psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python", "= kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema", "sheet to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not exist:", "- 1] elif arg == '--subsample-min': i += 2 process_subsample_min = args[i -", "%s\" % db_connection_string) print(\" Postgres Error: %s\" % e) return 1 #/* -----------------------------------------------------------------------", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "= row[map_def['column']] if value == 'INC': value = 'INCIDENT' return value #/* =======================================================================", "formatter: :type formatter: type|function :return: list of column names :rtype: list \"\"\" return", "function #/* ======================================================================= */# def print_usage(): \"\"\" Command line usage information :return: 1", "kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError):", "SEQNOS/reportnum being processed workbook XLRD workbook object The callable object specified in map_def['processing']['function']", "else: # Invalid argument i += 1 arg_error = True print(\"ERROR: Invalid argument:", "is required, simply grab the value from the sheet and add to the", "not download from URL: %s\" % download_url) print(\" URLLIB Error: %s\" % e)", "#/* ----------------------------------------------------------------------- */# #/* Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "handles all queries internally it can return '__NO_QUERY__' in order to be excluded", "the specified sheet - populate a NULL value value = db_null_value # Pass", "itself handles all queries internally it can return '__NO_QUERY__' in order to be", "more Row 2 Values' } { 'Column1': 'Row 3 Val', 'Column2': 'Another Row", "= 'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode =", "@staticmethod def areaid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None)", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "S, W) :type quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals =", "function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function called", "- tell parent process there's nothing left to do return initial_value_to_be_returned #/* -----------------------------------------------------------------------", "username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define", "Get the ordered column names from an XLRD sheet object :param sheet: XLRD", "field map # This query must be handled by the parent process so", ":return: list of elements, each containing one row of the sheet as a", "# copies or substantial portions of the Software. # # THE SOFTWARE IS", "it to nothing so the next test fails try: value = float(value) except", "SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage() function #/* ======================================================================= */# def", "pass # Get a list of unique report id's unique_report_ids = [] for", "False elif arg == '--no-execute-queries': i += 1 execute_queries = False # Additional", "value = float(value) except ValueError: value = '' # No sheen size -", "since # Build query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields =", "%s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT", "information to the processing function in order to get a result else: value", "kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the", "} } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name':", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"',", "NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column':", "%s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s =", "'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' }", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method #/*", "2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = '''", "# TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */#", "report_exists(**kwargs): \"\"\" Check to see if a report has already been submitted to", "'--h', '-h'): return print_help() elif arg in ('--usage', '-usage'): return print_usage() elif arg", "#/* Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download", "AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results =", "def recieved_datetime(**kwargs): \"\"\" See documentation for function called in the return statement \"\"\"", "1 overwrite_downloaded_file = True elif arg == '--subsample': i += 2 process_subsample =", "value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries,", "[] # Found a matching row if row[sheet_seqnos_field] == uid: # The first", "the workbook's sheets. The default column in 'CALLS' but can be specified by", "*/# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See", "a table :param seqnos: reportnum :type seqnos: int|float :param field: :type field: :return:", "associated documentation files (the \"Software\"), to deal # in the Software without restriction,", "*/# #/* Define main() function #/* ======================================================================= */# def main(args): \"\"\" Main routine", "class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None },", "specifying a specific target for the download, this flag is not needed due", "Spreadsheet I/O elif arg == '--no-download': i += 1 download_file = False elif", "default column in 'CALLS' but can be specified by the user. This set", "+= 1 print_queries = True print_progress = False elif arg == '--no-execute-queries': i", "use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "from an XLRD sheet object :param sheet: XLRD sheet object :type sheet: xlrd.Sheet", "a dictionary :rtype: dict \"\"\" output = [] columns = column_names(sheet) for r", "the query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes", "Password for database user [default: ''] --download-url URL from which to download the", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of", "in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value,", "validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB row", "'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS',", "return 1 # Prep workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r')", "= kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit =", "'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid }", "db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/* -----------------------------------------------------------------------", "def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/*", "to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "the Software without restriction, including without limitation the rights # to use, copy,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "kwargs['schema'] # TODO: replace this hack with something better. # Perhpas have a", "occurrences are sent to a different table - specified in the field map", "OTHER DEALINGS IN THE # SOFTWARE. # # =================================================================================== # \"\"\" Scraper for", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not", "Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target:", "'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static method #/* ----------------------------------------------------------------------- */#", "normalization by reading from a field containing \"1.23 METERS\" # This function takes", "sheet - populate a NULL value value = db_null_value # Pass all necessary", "from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude()", "arg == '--no-download': i += 1 download_file = False elif arg == '--download-url':", "@staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value',", "'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "# Build query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = []", "'NI': 5280, # Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping of", "map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else: # Get the", "def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define", "%s.%s WHERE %s = %s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall()) >", "'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS',", "{ # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, ], 'TABLE_NAME':", "process_subsample = args[i - 1] elif arg == '--subsample-min': i += 2 process_subsample_min", "======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some", "or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "script version information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\"", "this permission notice shall be included in all copies or substantial portions of", "of charge, to any person obtaining a copy # of this software and", "#/* Cache initial DB row counts for final stat printing #/* ----------------------------------------------------------------------- */#", "'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"',", "value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be sent directly", "NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */# # Database", "arg == '--db-name': i += 2 db_name = args[i - 1] elif arg", "= '' # No sheen size - nothing to do if value ==", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, {", "i += 1 print_progress = False elif arg == '--print-queries': i += 1", "be overwritten :type overwrite: bool :return: path to downloaded file :rtype: str|unicode \"\"\"", "#/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/*", "'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "provide better organization and to prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field'", "= kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache =", "*/# #/* Python setup #/* ======================================================================= */# if sys.version[0] is 2: range =", "db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #", "i += 2 db_connection_string = args[i - 1] elif arg == '--db-host': i", "validate_field_map_error = True print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name']) # Make", "*/# def print_help_info(): \"\"\" Print a list of help related flags :return: 1", "second. --file-to-process Specify where the input file will be downloaded to If used", "uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field", "an argument # 3. The arg parser did not properly iterate the 'i'", "value value = db_null_value # Pass all necessary information to the processing function", "that the value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be", "already exists and --no-download has not been specified, blindly overwrite the file. Unless", "Database - must be done here in order to allow the user to", "print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user", "'--subsample-min': i += 2 process_subsample_min = args[i - 1] # Positional arguments and", "Get a report number to process # Get a set of field maps", "to If used in conjunction with --no-download it is assumed that the specified", "*/# #/* Define print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\" Print a", "\" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field maps for one table", "*/# #/* Define column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get", "sheet object into a list of rows, each structured as a dictionary Example", "*/# #/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\"", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS", "'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema':", "True print(\"ERROR: Did not successfully parse arguments\") # Make sure the downloaded file", "%s\" % e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/*", "column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall()", "turns off the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" *", "% arg) # This catches three conditions: # 1. The last argument is", "except urllib2.URLError, e: print(\"ERROR: Could not download from URL: %s\" % download_url) print(\"", "the input file --overwrite-download If the --file-to-process already exists and --no-download has not", "documentation files (the \"Software\"), to deal in the Software without restriction, including without", "== '--no-download': i += 1 download_file = False elif arg == '--download-url': i", "in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output", "== '--db-name': i += 2 db_name = args[i - 1] elif arg ==", "to do so, subject to the following conditions: The above copyright notice and", "'\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, {", "\"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1", "# Assumed mistyping of 'IN' 'YARDS': 3 } # Database is expecting to", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "db_cursor.execute(query) # Done processing - update user if print_progress: print(\" - Done\") #/*", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code',", "notice and this permission notice shall be included in all # copies or", "the specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" %", "maps for a single table to process # Get a field map to", "as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More", "parent process there's nothing left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/*", "set to None if not used 'function': Callable object responsible for additional sub-processing", "['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i", "the sheet as a dictionary :rtype: dict \"\"\" output = [] columns =", "int \"\"\" print(__license__) return 1 #/* ======================================================================= */# #/* Define print_help() function #/*", "'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ {", "Each field map is applied against each ID which means that if ID", "NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "the target field. There should be one map for every field in a", "of the workbook's sheets. The default column in 'CALLS' but can be specified", "column in the database. These fields require an additional processing step that is", "in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source: %s -> %s.%s\" %", "Row 1 Values' }, { 'Column1': 'Row 2 Val', 'Column2': 'Another Row 2", "degrees: int :param minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds", "DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* =======================================================================", "have been processed Example bare minimum field map: The field map below shows", "Invalid subsample or subsample min - must be an int: %s\" % process_subsample)", "the query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'],", "print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + '", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from", "+= dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function #/* =======================================================================", "width for this field - used in string slicing 'db_schema': Name of target", "different table - specified in the field map arguments for e_db_map in extras_field_maps:", "this behavior is not required. If the function itself handles all queries internally", "because the entire # value is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\"", "processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries Print queries immediately", "' * (padding - len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts =", "not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite,", "return print_license() # Spreadsheet I/O elif arg == '--no-download': i += 1 download_file", "be inserted into which table in which schema. Each field map is applied", "kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value']", "Unless the user is specifying a specific target for the download, this flag", "Database is expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']]", "inserted into which table in which schema. Each field map is applied against", "Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final return #/* ----------------------------------------------------------------------- */# #", ":return: list of column names :rtype: list \"\"\" return [formatter(cell.value) for cell in", "======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet do not", "'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, #", "arg = args[i] # Help arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'):", "all parameters for an argument # 3. The arg parser did not properly", "user [default: ''] --download-url URL from which to download the input file --no-download", "def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database connection string :type cursor:", "dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees,", "print(__license__) return 1 #/* ======================================================================= */# #/* Define print_help() function #/* ======================================================================= */#", "#/* Process data #/* ----------------------------------------------------------------------- */# # Loops: # Get a report number", "' ' * (padding - len(schema_table) + 4), count)) print(\"New rows:\") for schema_table,", "----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\"", "#/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output = int(degrees)", "psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not connect to database: %s\"", "Scraper for the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user", "initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding - len(schema_table) +", "to allow the user to overwrite the default credentials and settings if db_connection_string", "field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping ...\")", "%s\" % e) return 1 # Prep workbook print(\"Opening workbook: %s\" % file_to_process)", "map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache,", "_coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require the same general logic. \"\"\"", "# Make sure the value is properly quoted if value not in (None,", "slicing 'db_schema': Name of target schema, 'sheet_name': Name of source sheet in input", "function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for", "a report number to process # Get a set of field maps for", "None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema':", "table 3. Process all field maps and assemble an insert query 4. Execute", "of a safety net if value is None or not value: value =", "as follows: All field maps = { 'table_name': [ { 'db_table': Name of", "a given ID is as follows: 1. Get an ID 2. Get a", "Skip first row since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c", "'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args':", "value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value is not a", "raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to the", "organization and to prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/*", "NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function", "\"\"\" output = [] columns = column_names(sheet) for r in range(1, sheet.nrows): #", "'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant':", "to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name()", "being processed workbook XLRD workbook object The callable object specified in map_def['processing']['function'] is", "int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return", "urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return destination #/* ======================================================================= */# #/*", "5280, 'NI': 5280, # Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping", "print_license() # Spreadsheet I/O elif arg == '--no-download': i += 1 download_file =", "======================================================================= */# def main(args): \"\"\" Main routine to parse, transform, and insert Current.xlsx", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation", "*/# __version__ = '0.1-dev' __release__ = 'August 8, 2014' __author__ = '<NAME>' __source__", "and longitude() methods require the same general logic. \"\"\" try: row = kwargs['row']", "kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet']", "'Column3': 'Even More Row 1 Values' }, { 'Column1': 'Row 2 Val', 'Column2':", "def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for permanent archival :param input_name:", "2 Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another Row", "used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of", "overwrite the file. Unless the user is specifying a specific target for the", "], 'TABLE_NAME': [ { 'db_table': Name of target table, 'db_field': Name of target", "requires parameters but the user did not supply the parameter # 2. The", "--db-host Hostname for the target database [default: localhost] --db-user Username used for database", "Postgres supported timestamp :param stamp: timestamp from XLRD reading a date encoded field", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing':", "in field_map[db_map]: # Don't need to process the reportnum information since it was", "'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static method #/* ----------------------------------------------------------------------- */#", "everything else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): #", "db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently only reads rows", "] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public',", "sure the downloaded file is not going to be accidentally deleted if download_file", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # =================================================================================== #", "'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS',", "# https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License (MIT) # #", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "#/* ----------------------------------------------------------------------- */# #/* Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "print_help_info(): \"\"\" Print a list of help related flags :return: 1 for exit", "*/# def print_help(): \"\"\" Detailed help information :return: 1 for exit code purposes", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function':", "tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\"", "target table, 'db_field': Name of target field, 'db_schema': Name of target schema, 'sheet_name':", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "2 process_subsample = args[i - 1] elif arg == '--subsample-min': i += 2", "has write permission to the target directory if not os.access(dirname(file_to_process), os.W_OK): bail =", "workbook: :type workbook: :param row: :type row: :param map_def: :type map_def: :rtype: :return:", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']]", "= kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec],", "Execute query, but not if the report already exists query = \"\"\"%s %s", "def print_help_info(): \"\"\" Print a list of help related flags :return: 1 for", "in the field map sheet_seqnos_field The field in all sheets containing the reportnum", "granted, free of charge, to any person obtaining a copy of this software", "'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public',", "multipliers = { 'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333,", "#/* ----------------------------------------------------------------------- */# # Database - must be done here in order to", "< len(args): try: arg = args[i] # Help arguments if arg in ('--help-info',", "@staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp to a Postgres", "quotes around specific values if isinstance(value, str) or isinstance(value, unicode): # Having single", "IN THE # SOFTWARE. # # =================================================================================== # \"\"\" Scraper for the \"temporary\"", "'-help', '--h', '-h'): return print_help() elif arg in ('--usage', '-usage'): return print_usage() elif", "'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, }", "= True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments", "function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method", "order to allow the user to overwrite the default credentials and settings if", "# # The above copyright notice and this permission notice shall be included", "\"Software\"), to deal # in the Software without restriction, including without limitation the", "etc. --version Version and ownership information --license License information \"\"\") return 1 #/*", "db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache", "should be one map for every field in a table. The structure for", "0 # User feedback settings print_progress = True print_queries = False execute_queries =", "same existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE", "__license__ = ''' The MIT License (MIT) Copyright (c) 2014 SkyTruth Permission is", "'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table':", "final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache all", "in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding - len(schema_table)", "'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO:", "db_null_value # Pass all necessary information to the processing function in order to", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "distribute, sublicense, and/or sell # copies of the Software, and to permit persons", "sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If no additional processing is required,", "'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with all options: This", "], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database", "workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish", "Process data #/* ----------------------------------------------------------------------- */# # Loops: # Get a report number to", "were encountered if bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection", "seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type degrees: int :param", "by table and center around the target field. There should be one map", "'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to the processing function in", "'-usage'): return print_license() # Spreadsheet I/O elif arg == '--no-download': i += 1", "Several methods require converting a timestamp to a Postgres supported timestamp format. This", "something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static method #/*", "field map states that a specific function must do more of the heavy", "Done processing - update user if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */#", "# value is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else:", "}, ], 'TABLE_NAME': [ { 'db_table': Name of target table, 'db_field': Name of", "of charge, to any person obtaining a copy of this software and associated", "deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s", "}, { # TODO: Implement - check notes about which column to use", "main.__doc__)) return 1 #/* ======================================================================= */# #/* Define print_help_info() function #/* ======================================================================= */#", "the heavy lifting. Field maps are grouped by table and center around the", "portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "String value else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something", "= (None, '', u'') for iv in illegal_vals: if iv in (degrees, minutes,", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ]", "= args[i - 1] elif arg == '--file-to-process': i += 2 file_to_process =", "kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */#", "'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"',", "'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "permit persons to whom the Software is # furnished to do so, subject", "of this utility --usage Arguments, parameters, flags, options, etc. --version Version and ownership", "to handle the normalization by reading from a field containing \"1.23 METERS\" #", "'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping of 'MI' 'UN': 0.0833333,", "Field maps are grouped by table and center around the target field. There", "execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/* ======================================================================= */# #/*", "- 1] elif arg == '--db-user': i += 2 db_user = args[i -", "inserts and destroy DB connections # db_conn.commit() # connection is now set to", "--db-user Username used for database connection [default: current user] --db-name Name of target", "field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache = {}", "= False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */#", "'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field':", "'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"':", "\"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet()", "insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value)", "%s = %s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall()) > 0 #/*", "entire # value is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value)", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "general logic. \"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes']", "3600 if quadrant.lower() in ('s', 'w'): output *= -1 return output #/* =======================================================================", "----------------------------------------------------------------------- */# # Database db_connection_string = None db_host = 'localhost' db_name = 'skytruth'", "No sheen size - nothing to do if value == '' or unit", "*/# #/* Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): #", "process # Get a field map to process print(\"Processing workbook ...\") num_ids =", "a set of field maps for one target table 3. Process all field", "Process all field maps and assemble an insert query 4. Execute the insert", "and center around the target field. There should be one map for every", "the field map but this behavior is not required. If the function itself", "= kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace this hack with something", "print the progress indicator --print-queries Print queries immediately before execution Automatically turns off", "test if map_def['sheet_name'] is not None and map_def['column'] is not None: try: sheet", "This query must be handled by the parent process so this value is", "keys and drive processing. Rather than process the input document sheet by sheet", "% file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB connection and", "# Loops: # Get a report number to process # Get a set", "Current.xlsx name for permanent archival :param input_name: input file name (e.g. Current.xlsx) :type", "'db_field': Name of target field, 'db_schema': Name of target schema, 'sheet_name': Name of", "value = 'INCIDENT' return value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/*", "Define print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\" Command line usage information", "not in (None, '', u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode): value", "#/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row']", "#/* Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\"", "Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another Row 2", "'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public',", "'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'}", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "# Update user padding = max([len(i) for i in field_map.keys()]) indent = \"", "if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific", "None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"',", "xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of being inserted into Postgres timestamp", "Overwrite=%s and outfile exists: %s\" % (overwrite, destination)) # Download response = urllib2.urlopen(url)", "Name of source column in sheet_name, 'processing': { # Optional - should be", "progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1", "options elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file = True elif arg", "processing - update user if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/*", "restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,", "======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant", "Print a list of help related flags :return: 1 for exit code purposes", "arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps']", "\"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname]", "process the input document sheet by sheet and row by row, a set", "{'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema':", "must do more of the heavy lifting. Field maps are grouped by table", "db_connection_string = args[i - 1] elif arg == '--db-host': i += 2 db_host", "Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i,", "======================================================================= */# def print_help_info(): \"\"\" Print a list of help related flags :return:", "necessary to execute one of these processing functions. A class is used as", "sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for", "map to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i = 0 #", "sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/*", "USE OR OTHER DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define", "db_user = getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum'", "'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS',", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "NrcParsedReportFields.areaid } }, { # TODO: Implement - check notes about which column", "# Encountered an error validating the field map if validate_field_map_error: db_cursor.close() db_conn.close() return", "- structured just like a csv.DictReader row sheet The entire sheet from which", "try: value = float(value) except ValueError: value = '' # No sheen size", "elsewhere so this is more of a safety net if value is None", "}, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ {", "for downloaded file :type destination: str|unicode :param overwrite: specify whether or not an", "'\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area,", "'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "the Software without restriction, including without limitation the rights to use, copy, modify,", "\"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static", "'\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url", "% value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute", "iv in illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal", "step that is highly specific and cannot be re-used. The field map definition", "map_def Current map definition being processed (example below) print_queries Specifies whether or not", "# TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "structure for field maps is roughly as follows: All field maps = {", "os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample =", "a namespace to provide better organization and to prevent having to name functions", "bool :return: path to downloaded file :rtype: str|unicode \"\"\" # Validate arguments if", "immediately before execution Automatically turns off the progress indicator --no-execute-queries Don't execute queries", ":param stamp: timestamp from XLRD reading a date encoded field :type stamp: float", "detailed description of this utility --usage Arguments, parameters, flags, options, etc. --version Version", "None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/*", "to a Postgres supported timestamp format. This method eliminates repitition :param workbook: :type", "set of SEQNOS/reportnum's are gathered from one of the workbook's sheets. The default", ":rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__))", "(sys.argv[1:] in order to drop the script name) :type args: list :return: 0", "\"\"\" # Validate arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and", "functions. A class is used as a namespace to provide better organization and", "uid = kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def", "'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS',", "object :param sheet: XLRD sheet object :type sheet: xlrd.Sheet :param formatter: :type formatter:", "None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema':", "database connection [default: current user] --db-name Name of target database [default: skytruth] --db-pass", "more Row 3 Values' } ] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name')", "'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args':", "sheet and add to the query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "be used for all queries db_null_value Value to use for NULL db_seqnos_field The", "float \"\"\" illegal_vals = (None, '', u'') for iv in illegal_vals: if iv", "return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function #/* ======================================================================= */# def", "Command line usage information :return: 1 for exit code purposes :rtype: int \"\"\"", "The MIT License (MIT) Copyright (c) 2014 SkyTruth Permission is hereby granted, free", "as they are executed raw_sheet_cache Structured similar to the normal sheet cache, but", "the value is not a float, change it to nothing so the next", "f.write(response.read()) return destination #/* ======================================================================= */# #/* Define name_current_file() function #/* ======================================================================= */#", "'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table':", "column in 'CALLS' but can be specified by the user. This set of", "before execution Automatically turns off the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__,", "if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process)", "#/* Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD", "value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method", "i += 2 file_to_process = abspath(args[i - 1]) # Database connection elif arg", "'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema':", "DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e:", "The default column in 'CALLS' but can be specified by the user. This", "a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller()", "= False # Additional options elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file", "map_def['sheet_name'] is not None and map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name'])", "'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep", "longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* =======================================================================", "lifting. Field maps are grouped by table and center around the target field.", ":rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/* ----------------------------------------------------------------------- */#", "must be done here in order to allow the user to overwrite the", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None", "must be an int: %s\" % process_subsample) # Exit if any problems were", "db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError:", "for db_map in field_map_order: query_fields = [] query_values = [] # If the", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { # TODO: Not populated", "system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of SEQNOS/reportnum's are gathered from", "initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = []", "cause problems on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass", "arguments were properly parse if arg_error: bail = True print(\"ERROR: Did not successfully", "{ 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name':", "NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table':", "if execute_queries: db_cursor.execute(query) # Done processing - update user if print_progress: print(\" -", "method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/'", "the value is properly quoted if value not in (None, '', u'', db_null_value):", "i += 2 process_subsample_min = args[i - 1] # Positional arguments and errors", "*/# class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map", "value to be inserted into the target field described in the field map", "] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list", "%s\" % arg) # This catches three conditions: # 1. The last argument", "#/* ======================================================================= */# #/* Define print_version() function #/* ======================================================================= */# def print_version(): \"\"\"", "@staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def = kwargs['map_def'] row =", "======================================================================= */# __version__ = '0.1-dev' __release__ = 'August 8, 2014' __author__ = '<NAME>'", "def print_help(): \"\"\" Detailed help information :return: 1 for exit code purposes :rtype:", "# Copyright (c) 2014 SkyTruth # # Permission is hereby granted, free of", "download_file = True process_subsample = None process_subsample_min = 0 # User feedback settings", "'--db-pass': i += 2 db_pass = args[i - 1] # Commandline print-outs elif", "{ 'db_table': Name of target table, 'db_field': Name of target field, 'db_schema': Name", "for s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids))", "areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement -", "db_connection_string = None db_host = 'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass", "quadrant (N, E, S, W) :type quadrant: str|unicode :return: decimal degrees :rtype: float", "print(\" URLLIB Error: %s\" % e) return 1 # Prep workbook print(\"Opening workbook:", "extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode,", "user] --db-name Name of target database [default: skytruth] --db-pass Password for database user", "schema_table + ' ' * (padding - len(schema_table) + 4), count)) print(\"Final row", "\"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */#", "directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes around the table", "for function called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */#", "1 Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even More Row 1 Values'", "('s', 'w'): output *= -1 return output #/* ======================================================================= */# #/* Define column_names()", "Did not successfully parse arguments\") # Make sure the downloaded file is not", "'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url',", "'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS',", "is more of a safety net if value is None or not value:", "\", \".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception as e: print (\"Error", "it was added to the initial query above if map_def['db_field'] == db_seqnos_field: query_fields", "W) :type quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals = (None,", "NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\"", "Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None)", "value is None or not value: value = db_null_value # Assemble query if", "but with a list of rows instead of a dictionary containing reportnums as", "======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet do not", "int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order", "* 2 print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent,", "uid_i = 0 # Loop through the primary keys for uid in unique_report_ids:", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "--license License information \"\"\") return 1 #/* ======================================================================= */# #/* Define print_version() function", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "*/# # Pass all necessary information to the processing function in order to", "False print(\"Validating field mapping ...\") for db_map in field_map_order: # Check each field", "specified in map_def['processing']['function'] is responsible for ALL queries. The processing functions are intended", "input file, 'column': Name of source column in sheet_name, 'processing': { # Optional", "table, skip everything else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema,", "======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for permanent archival", "parameter, 'Arg2': ... } } }, { 'db_table': Name of target table, 'db_field':", "'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } }", "the input file --no-download Don't download the input file --overwrite-download If the --file-to-process", "len(args): try: arg = args[i] # Help arguments if arg in ('--help-info', '-help-info',", "field map below shows that the value in the 'RESPONSIBLE_COMPANY' column in the", "to deal # in the Software without restriction, including without limitation the rights", "'processing': { # Optional - should be set to None if not used", "or not queries should actually be executed map_def Current map definition being processed", "test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not exist: %s\" %", "% (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the sheet to test except", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons", "assemble an insert query 4. Execute the insert statement 5. Repeat steps 2-4", "sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define", "bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* =======================================================================", "extra_query_fields.append(e_map_def['db_field']) # Do something with the query query = \"\"\"%s %s.%s (%s) VALUES", "encountered if bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection and", "Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value", "return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB row counts for final", "% value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the query query", "the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\"", "overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite, destination))", "to verify everything was wroking unique_report_ids = [i for i in unique_report_ids if", "*/# if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: # UID", "than process the input document sheet by sheet and row by row, a", "sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/*", "print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\" Print a list of help", "illegal_vals = (None, '', u'') for iv in illegal_vals: if iv in (degrees,", "workbook: # Establish a DB connection and turn on dict reading db_conn =", "this software and associated documentation files (the \"Software\"), to deal # in the", "described in the field map sheet_seqnos_field The field in all sheets containing the", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY',", "default credentials and settings if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s'", "#/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, {", "#/* ----------------------------------------------------------------------- */# i = 0 arg_error = False while i < len(args):", "for permanent archival :param input_name: input file name (e.g. Current.xlsx) :type input_name: str|unicode", "granted, free of charge, to any person obtaining a copy # of this", "#/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define", "for NULL db_seqnos_field The reportnum field in the database db_write_mode The first part", "into the target field described in the field map but this behavior is", "(padding - len(schema_table) + 4), count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems():", "illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\"", "query must be handled by the parent process so this value is #", "off the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__)))", "'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing':", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "the commandline (sys.argv[1:] in order to drop the script name) :type args: list", "set to schema.table db_cursor The cursor to be used for all queries db_null_value", "to execute one of these processing functions. A class is used as a", "all queries db_null_value Value to use for NULL db_seqnos_field The reportnum field in", "'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} }", "%s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR:", "document is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The", "Build information #/* ======================================================================= */# __version__ = '0.1-dev' __release__ = 'August 8, 2014'", "#/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/*", "minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type degrees: int", ":rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field", "without restriction, including without limitation the rights # to use, copy, modify, merge,", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN',", "# Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS':", "Define main() function #/* ======================================================================= */# def main(args): \"\"\" Main routine to parse,", "3 Values\" Example Output: [ { 'Column1': 'Row 1 Val', 'Column2': 'Another Row", "furnished to do so, subject to the following conditions: The above copyright notice", "#/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\"", "%s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */#", "return #/* ----------------------------------------------------------------------- */# # Update user padding = max([len(i) for i in", "----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement - currently returning NULL return", "permit persons to whom the Software is furnished to do so, subject to", "row if row[sheet_seqnos_field] == uid: # The first instance goes into the table", "and --no-download has not been specified, blindly overwrite the file. Unless the user", "field map arguments for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value =", "ID number 1234 is being processed, the bare minimum field map example below", "processed workbook XLRD workbook object The callable object specified in map_def['processing']['function'] is responsible", "NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url))", "'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"',", "to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id()", "*/# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return", "https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License (MIT) # # Copyright", "the row was extracted as described in the field map sheet_seqnos_field The field", "#/* Prep DB connection and XLRD workbook for processing #/* ----------------------------------------------------------------------- */# #", "insert query 4. Execute the insert statement 5. Repeat steps 2-4 until all", "information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0}", "be an int: %s\" % process_subsample) # Exit if any problems were encountered", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */#", "\"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\" Example Output: [", "something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static method #/*", "list of rows instead of a dictionary containing reportnums as keys and rows", "Print out license information :return: 1 for exit code purposes :rtype: int \"\"\"", "_coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude()", "maps using additional processing always receive the following kwargs: all_field_maps All field maps", "*/# #/* Define print_license() function #/* ======================================================================= */# def print_license(): \"\"\" Print out", "arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in", "(db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception", "about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "= kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError,", "shall be included in all # copies or substantial portions of the Software.", "1] elif arg == '--db-host': i += 2 db_host = args[i - 1]", "'INCIDENT' return value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/* ======================================================================= */#", "float(value) except ValueError: value = '' # No sheen size - nothing to", "coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define", "argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */#", "field_map[db_map]: # Don't need to process the reportnum information since it was added", "len(unique_report_ids): # TODO: Delete constraining line - needed to verify everything was wroking", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column':", "mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3 }", "----------------------------------------------------------------------- */# #/* Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs):", "See documentation for function called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/*", "True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) #", "# Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, { 'db_table': Name", "unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum)", "Cache all sheets needed by the field definitions as dictionaries print(\"Caching sheets ...\")", "# Having single quotes in the string causes problems on insert because the", "'\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, {", "value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static", "any person obtaining a copy # of this software and associated documentation files", "''' #/* ======================================================================= */# #/* Define print_usage() function #/* ======================================================================= */# def print_usage():", "= %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s", "= db_null_value # Assemble query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) #", "'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name':", "3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping of", "field maps with keys set to schema.table db_cursor The cursor to be used", "= kwargs['schema'] # TODO: replace this hack with something better. # Perhpas have", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ],", "#/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a NULL value", "reportnum :type seqnos: int|float :param field: :type field: :return: :rtype: bool \"\"\" reportnum", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False", "Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\"", "db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently", "\"\"\" print(\"\"\" Help flags: --help More detailed description of this utility --usage Arguments,", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "one row of the sheet as a dictionary :rtype: dict \"\"\" output =", "c in range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define report_exists() function #/*", "datetime import datetime import getpass import os from os.path import * import sys", "already exists and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "= args[i - 1] elif arg == '--subsample-min': i += 2 process_subsample_min =", "{ # Optional - should be set to None if not used 'function':", "is 2: range = xrange #/* ======================================================================= */# #/* Build information #/* =======================================================================", "from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields()", "report number to process # Get a set of field maps for a", "multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET' #/* ----------------------------------------------------------------------- */#", "method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/*", "\"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */#", "to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes around the table name.", "\"1.23 METERS\" # This function takes care of that but must still supply", "of the Software, and to permit persons to whom the Software is furnished", "maps is roughly as follows: All field maps = { 'table_name': [ {", "current row being processed - structured just like a csv.DictReader row sheet The", "5280, # Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN'", "limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or", "'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public',", "'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name':", "'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp }", "contains all of the additional arguments and information necessary to execute one of", "db_map in field_map_order: # Check each field definition in the set of mappings", "'\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length,", "function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/* -----------------------------------------------------------------------", "schema, 'sheet_name': Name of source sheet in input file, 'column': Name of source", "must be passed to the NrcParsedReportFields.longitude() function where the actual processing happens. Field", "#/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error", "#/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function called in", "normal sheet cache, but with a list of rows instead of a dictionary", "Some fields in the NRC spreadsheet do not map directly to a column", "import psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python setup #/*", ":type degrees: int :param minutes: coordinate minutes :type minutes: int :param seconds: coordinate", "if not used 'function': Callable object responsible for additional sub-processing 'args': { #", "except IndexError: # Sheet was empty pass # Get a list of unique", "the field map sheet_seqnos_field The field in all sheets containing the reportnum uid", "be set to None if not used 'function': Callable object responsible for additional", "to None if not used 'function': Callable object responsible for additional sub-processing 'args':", "'-usage'): return print_usage() elif arg in ('--version', '-version'): return print_version() elif arg in", "input file will be downloaded to If used in conjunction with --no-download it", "Get a list of unique report id's unique_report_ids = [] for s_name, s_rows", "query_fields = [db_seqnos_field] query_values = [str(uid)] else: # Get the row for this", "----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ {", "object specified in map_def['processing']['function'] is responsible for ALL queries. The processing functions are", "args: arguments from the commandline (sys.argv[1:] in order to drop the script name)", "Python setup #/* ======================================================================= */# if sys.version[0] is 2: range = xrange #/*", "query_values = [] # If the report already exists, in the target table,", "License information \"\"\") return 1 #/* ======================================================================= */# #/* Define print_version() function #/*", "coordinate seconds :type seconds: int :param quadrant: coordinate quadrant (N, E, S, W)", "try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not connect", "'INC': value = 'INCIDENT' return value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class", "except Exception as e: print (\"Error printing SQL query to console (unicode weirdness?\")", "distribute, sublicense, and/or sell copies of the Software, and to permit persons to", "#/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted", "kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid']", "by the user. This set of ID's are treated as primary keys and", "field map is applied against each ID which means that if ID number", "db_seqnos_field The reportnum field in the database db_write_mode The first part of the", "- 1] elif arg == '--db-host': i += 2 db_host = args[i -", "'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema':", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "shall be included in all copies or substantial portions of the Software. THE", "----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\"", "and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "reportnum field in the database db_write_mode The first part of the SQL statement", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If no additional", "# Download response = urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return destination", "@staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static", "\"\"\" The latitude() and longitude() methods require the same general logic. \"\"\" try:", "similar to the normal sheet cache, but with a list of rows instead", "file name (e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted name :rtype: str|unicode", "flags :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help flags:", "# Perhpas have a report_exists method on each of the field map classes", "None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "args[i - 1] elif arg == '--db-name': i += 2 db_name = args[i", "insert statement 5. Repeat steps 2-4 until all tables have been processed Example", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema':", "hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string", "'column': 'CHRIS_CODE', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "sys import urllib2 import psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */# #/*", "Copyright (c) 2014 SkyTruth # # Permission is hereby granted, free of charge,", "*/# def download(url, destination, overwrite=False): \"\"\" Download a file :param url: URL to", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require", "'Arg2': ... } } } ], } The order of operations for a", "execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None:", "are declared to describe which fields in which sheets should be inserted into", "latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from", "(N, E, S, W) :type quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\"", "must still supply the expected post-normalization format if unit.upper() not in multipliers: return", "row counts for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor,", "map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the", "roughly as follows: All field maps = { 'table_name': [ { 'db_table': Name", "\\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query)", "= unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */#", "value = row[map_def['column']] except KeyError: # UID doesn't appear in the specified sheet", "# Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" %", "#/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map", "the script name) :type args: list :return: 0 on success and 1 on", "prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/*", "done here in order to allow the user to overwrite the default credentials", "not value: value = db_null_value # Assemble query if value not in ('__NO_QUERY__',", ":type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return: number of rows", "--db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__ import division from __future__", "to be inserted into the target field described in the field map but", "schema_table + ' ' * (padding - len(schema_table) + 4), count)) print(\"New rows:\")", "Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even more Row 2 Values' }", "return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod", "'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name':", "value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/*", "}, { 'db_table': Name of target table, 'db_field': Name of target field, 'db_schema':", "field map sheet_seqnos_field The field in all sheets containing the reportnum uid The", "Values' }, { 'Column1': 'Row 2 Val', 'Column2': 'Another Row 2 Val', 'Column3':", "unit = row[map_def['processing']['args']['unit_field']] # If the value is not a float, change it", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries Print", "Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert", "IndexError: i += 1 arg_error = True print(\"ERROR: An argument has invalid parameters\")", "down to the second. --file-to-process Specify where the input file will be downloaded", "database connection string :type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return:", "'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public',", "return print_help_info() elif arg in ('--help', '-help', '--h', '-h'): return print_help() elif arg", "shows that the value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can", "__docname__ = basename(__file__) __license__ = ''' The MIT License (MIT) Copyright (c) 2014", "print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\" Command line usage information :return:", "- commit inserts and destroy DB connections # db_conn.commit() # connection is now", "print(\"ERROR: Invalid argument: %s\" % arg) # This catches three conditions: # 1.", "- populate a NULL value value = db_null_value # Pass all necessary information", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "======================================================================= */# #/* Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some", "(map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error =", "in range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define report_exists() function #/* =======================================================================", "= abspath(args[i - 1]) # Database connection elif arg == '--db-connection-string': i +=", "NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/*", "3 Val\",\"Even More Row 3 Values\" Example Output: [ { 'Column1': 'Row 1", "print_queries = True print_progress = False elif arg == '--no-execute-queries': i += 1", "\"\"\" Print script version information :return: 1 for exit code purposes :rtype: int", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None },", "float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of being", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "if iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" %", "# TODO: replace this hack with something better. # Perhpas have a report_exists", "'\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id,", "#/* ----------------------------------------------------------------------- */# #/* Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "they are executed raw_sheet_cache Structured similar to the normal sheet cache, but with", "information --license License information \"\"\") return 1 #/* ======================================================================= */# #/* Define print_version()", "query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to the insert", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field':", "so, subject to the following conditions: # # The above copyright notice and", "i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/*", "statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* -----------------------------------------------------------------------", "This field map shows that no specific column contains the value required for", "'\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, {", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "# Get a single field map to process for map_def in field_map[db_map]: #", "row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */#", "copy # of this software and associated documentation files (the \"Software\"), to deal", "not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single field map to process", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done processing - update", "1 download_file = False elif arg == '--download-url': i += 2 download_url =", "import * import sys import urllib2 import psycopg2 import psycopg2.extras import xlrd #/*", "...\") sheet_cache = {} raw_sheet_cache = {} for sname in workbook.sheet_names(): if sname", "field map definition contains all of the additional arguments and information necessary to", "Postgres supported connection string. All other --db-* options are ignored. --db-host Hostname for", "= True print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name']) # Make sure", "in ('--usage', '-usage'): return print_usage() elif arg in ('--version', '-version'): return print_version() elif", "quotes in the string causes problems on insert because the entire # value", "print_license(): \"\"\" Print out license information :return: 1 for exit code purposes :rtype:", "map definition contains all of the additional arguments and information necessary to execute", "The field map definition contains all of the additional arguments and information necessary", "map_def['sheet_name'], map_def['column'])) # Could not get the sheet to test except xlrd.XLRDError: validate_field_map_error", "workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of being inserted into", "(MIT) # # Copyright (c) 2014 SkyTruth # # Permission is hereby granted,", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args':", "----------------------------------------------------------------------- */# #/* Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs):", "'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, {", "kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field']", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "process so this value is # returned at the very end if initial_value_to_be_returned", "returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static method", "method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def']", "#/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the ordered column names from", "is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent to a different", "get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download a file", "map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR: Invalid", "sheet_name, 'processing': { # Optional - should be set to None if not", "'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "from which the row was extracted as described in the field map sheet_seqnos_field", "downloaded file :rtype: str|unicode \"\"\" # Validate arguments if not overwrite and isfile(destination):", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT',", "bail = False # Make sure arguments were properly parse if arg_error: bail", "map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode", "format. This method eliminates repitition :param workbook: :type workbook: :param row: :type row:", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "arguments and errors else: # Invalid argument i += 1 arg_error = True", "An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/* -----------------------------------------------------------------------", "SQL statement for writes (e.g. INSERT INTO) execute_queries Specifies whether or not queries", "db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database connection string :type cursor: psycopg2.cursor", "# copies of the Software, and to permit persons to whom the Software", "Perhpas have a report_exists method on each of the field map classes so", "float formatted date a Postgres supported timestamp :param stamp: timestamp from XLRD reading", "the field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache =", "__source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The MIT License (MIT)", "# If no additional processing is required, simply grab the value from the", "not required. If the function itself handles all queries internally it can return", "db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field", "= 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The MIT License (MIT) Copyright", "#/* ======================================================================= */# #/* Python setup #/* ======================================================================= */# if sys.version[0] is 2:", ":type quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals = (None, '',", "# Database - must be done here in order to allow the user", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "TODO: Use 24 hour time workbook = kwargs['workbook'] row = kwargs['row'] map_def =", "#/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation", "to the query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value", "'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name':", "----------------------------------------------------------------------- */# #/* Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs):", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "needed due the default file name containing datetime down to the second. --file-to-process", "in the field map arguments for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]:", "NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, } }, {", "0 # Loop through the primary keys for uid in unique_report_ids: # Update", "kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache']", "if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final return", "argument # 3. The arg parser did not properly iterate the 'i' variable", "'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds':", "'reportnum') schema = kwargs['schema'] # TODO: replace this hack with something better. #", "in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row", "weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done processing - update user if", "a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional", "field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values", "r in range(1, sheet.nrows): # Skip first row since it contains the header", "return value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/* ======================================================================= */# class", "return unicode(multipliers[unit.upper()] * value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length()", "IndexError: # Sheet was empty pass # Get a list of unique report", "arg in ('--help', '-help', '--h', '-h'): return print_help() elif arg in ('--usage', '-usage'):", "None or not value: value = db_null_value # Assemble query if value not", "http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of SEQNOS/reportnum's are gathered from one", "return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static method #/* ----------------------------------------------------------------------- */#", "already been submitted to a table :param seqnos: reportnum :type seqnos: int|float :param", "uid in unique_report_ids: # Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" +", "# =================================================================================== # # # The MIT License (MIT) # # Copyright (c)", "problems were encountered if bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB", "sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError: # Sheet", "exists and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the", "additional processing. Note the quotes around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "'CHRIS_CODE', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount',", "Validate arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists:", "target directory if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write permission", "xrange #/* ======================================================================= */# #/* Build information #/* ======================================================================= */# __version__ = '0.1-dev'", "workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def", "The first instance goes into the table specified in the field map #", "''' The MIT License (MIT) Copyright (c) 2014 SkyTruth Permission is hereby granted,", "function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into", "Current map definition being processed (example below) print_queries Specifies whether or not queries", "db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field", "'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid }", "#/* ----------------------------------------------------------------------- */# bail = False # Make sure arguments were properly parse", "expected post-normalization format if unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] *", "class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly", "'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS',", "full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url()", "Additional prep #/* ----------------------------------------------------------------------- */# # Cache all sheets needed by the field", "Could not download from URL: %s\" % download_url) print(\" URLLIB Error: %s\" %", "specific column contains the value required for public.\"NrcParsedReport\".longitude Instead, some information must be", "has already been submitted to a table :param seqnos: reportnum :type seqnos: int|float", "- currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter()", "sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value", "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,", "i += 1 arg_error = True print(\"ERROR: Invalid argument: %s\" % arg) #", "arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\"", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO:", "[db_seqnos_field] query_values = [str(uid)] else: # Get the row for this sheet try:", "'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"',", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table':", "*/# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary", "the insert statement 5. Repeat steps 2-4 until all tables have been processed", "os from os.path import * import sys import urllib2 import psycopg2 import psycopg2.extras", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"',", "name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample = None process_subsample_min = 0", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema':", "2 Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even more Row 2 Values'", "Database db_connection_string = None db_host = 'localhost' db_name = 'skytruth' db_user = getpass.getuser()", "'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name':", "processing always receive the following kwargs: all_field_maps All field maps with keys set", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "# TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor", "{ 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, {", "def incident_datetime(**kwargs): \"\"\" See documentation for function called in the return statement \"\"\"", "= value.replace(\"'\", '\"') # Single quotes cause problems on insert try: if e_map_def['db_field_width']:", "NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing", "\"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "All field maps = { 'table_name': [ { 'db_table': Name of target table,", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public',", "%s \"\"\" % (__docname__, __version__, __release__)) return 1 #/* ======================================================================= */# #/* Define", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "'--no-execute-queries': i += 1 execute_queries = False # Additional options elif arg ==", "More Row 2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row 3", "a float formatted date a Postgres supported timestamp :param stamp: timestamp from XLRD", "print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if", "file already exists and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't", "Pass all necessary information to the processing function in order to get a", "the following conditions: The above copyright notice and this permission notice shall be", "value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query,", "Values\" Example Output: [ { 'Column1': 'Row 1 Val', 'Column2': 'Another Row 1", "'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS',", "the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host", "db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS'", "This document is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # #", "documentation for function called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* -----------------------------------------------------------------------", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': {", "map # This query must be handled by the parent process so this", "included in all copies or substantial portions of the Software. THE SOFTWARE IS", "as a namespace to provide better organization and to prevent having to name", "If the report already exists, in the target table, skip everything else _schema,", "an error validating the field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/*", "list :return: 0 on success and 1 on error :rtype: int \"\"\" #/*", "sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] =", ":return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info]", "2 Val', 'Column3': 'Even more Row 2 Values' } { 'Column1': 'Row 3", "#/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required", "where the actual processing happens. Field maps using additional processing always receive the", "value not in (None, '', u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode):", ":param row: :type row: :param map_def: :type map_def: :rtype: :return: \"\"\" # TODO:", "[str(uid)] else: # Get the row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid]", "- len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts)", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': {", "%s\" % iv) if quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR:", "None process_subsample_min = 0 # User feedback settings print_progress = True print_queries =", "= kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: #", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "[--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres supported connection", "'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { # TODO:", "'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public',", "i += 2 db_name = args[i - 1] elif arg == '--db-pass': i", "sheet.nrows): # Skip first row since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c))", "'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"',", "row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make", "print(\"ERROR: Did not successfully parse arguments\") # Make sure the downloaded file is", "#/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table':", "field map to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i = 0", "> 0 #/* ======================================================================= */# #/* Define timestamp2datetime() function #/* ======================================================================= */# def", "xlrd.Sheet :param formatter: :type formatter: type|function :return: list of column names :rtype: list", "s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if necessary if process_subsample", "- len(schema_table) + 4), count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\"", "/ 60 + int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output *=", "'\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, {", "specific target for the download, this flag is not needed due the default", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS", "not map directly to a column in the database. These fields require an", "the second. --file-to-process Specify where the input file will be downloaded to If", "field, 'db_schema': Name of target schema, 'sheet_name': Name of source sheet in input", "better. # Perhpas have a report_exists method on each of the field map", "= workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find", "} } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name':", "db_name = args[i - 1] elif arg == '--db-pass': i += 2 db_pass", "# If the report already exists, in the target table, skip everything else", "Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even more Row 3 Values' }", "#/* Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in", "'-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help', '-help', '--h', '-h'): return", "counts for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts)", "everything was wroking unique_report_ids = [i for i in unique_report_ids if i >", "VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\")", "int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result =", "a specific function must do more of the heavy lifting. Field maps are", "cursor = kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema']", "is highly specific and cannot be re-used. The field map definition contains all", "the report already exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ %", "'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None },", "#/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if the", "'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"',", "print(query) except Exception as e: print (\"Error printing SQL query to console (unicode", "* len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/* Define print_help_info() function #/*", "'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { # TODO:", ":param field: :type field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor =", "sure schema and table exist in the DB query = \"SELECT * FROM", "# =================================================================================== # \"\"\" Scraper for the \"temporary\" NRC incident spreadsheet Sample command:", "\"\"\" Convert an XLRD sheet object into a list of rows, each structured", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime',", "'TABLE_NAME': [ { 'db_table': Name of target table, 'db_field': Name of target field,", "i < len(args): try: arg = args[i] # Help arguments if arg in", ":param sheet: XLRD sheet object :type sheet: xlrd.Sheet :param formatter: :type formatter: type|function", "value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries,", "quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" %", "something with the query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode,", "i += 1 arg_error = True print(\"ERROR: An argument has invalid parameters\") #/*", "'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema':", "*/# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row = kwargs['row'] map_def", ":return: output formatted name :rtype: str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\")", "2. The arg parser did not properly consume all parameters for an argument", "to whom the Software is # furnished to do so, subject to the", "order to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value,", "be included in all # copies or substantial portions of the Software. #", "quadrant: %s\" % quadrant) output = int(degrees) + int(minutes) / 60 + int(seconds)", "@staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require the same general", "user did not supply the parameter # 2. The arg parser did not", "'i' variable except IndexError: i += 1 arg_error = True print(\"ERROR: An argument", "function #/* ======================================================================= */# def main(args): \"\"\" Main routine to parse, transform, and", "an existing destination should be overwritten :type overwrite: bool :return: path to downloaded", "arg parser did not properly consume all parameters for an argument # 3.", "MIT License (MIT) Copyright (c) 2014 SkyTruth Permission is hereby granted, free of", "print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map", "None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER',", "have the same existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM", "isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file,", "kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace this hack with something better.", "to return a final value to be inserted into the target field described", "cannot be re-used. The field map definition contains all of the additional arguments", "converting a timestamp to a Postgres supported timestamp format. This method eliminates repitition", "if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and", "[--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres supported connection string.", "'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public',", "'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS',", "# Make sure the downloaded file is not going to be accidentally deleted", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "= False # Make sure arguments were properly parse if arg_error: bail =", "input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function #/*", "password='%s'\" % (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/*", "== '--db-connection-string': i += 2 db_connection_string = args[i - 1] elif arg ==", "----------------------------------------------------------------------- */# #/* Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs):", "raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value =", "of target database [default: skytruth] --db-pass Password for database user [default: ''] --download-url", "in sheet_name, 'processing': { # Optional - should be set to None if", "connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not connect to database: %s\" %", "return 0 #/* ======================================================================= */# #/* Commandline Execution #/* ======================================================================= */# if __name__", "def print_license(): \"\"\" Print out license information :return: 1 for exit code purposes", "XLRD sheet object :type sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return: list", "responsible for ALL queries. The processing functions are intended to return a final", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT',", "method on each of the field map classes so we don't have to", "return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/*", "'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None },", "*/# #/* Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'):", "the user. This set of ID's are treated as primary keys and drive", "WHERE %s = %s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall()) > 0", "response = urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return destination #/* =======================================================================", "statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these should be handled", "#/* Build information #/* ======================================================================= */# __version__ = '0.1-dev' __release__ = 'August 8,", "----------------------------------------------------------------------- */# # Cache all sheets needed by the field definitions as dictionaries", "currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static", "material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments map_def", "about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "(padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts", "======================================================================= */# #/* Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some", "files (the \"Software\"), to deal # in the Software without restriction, including without", "unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET'", "for exit code purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__,", "{ 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name':", "{ 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD'", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "if any problems were encountered if bail: return 1 #/* ----------------------------------------------------------------------- */# #/*", "'CALLS' but can be specified by the user. This set of ID's are", "pass extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\" % value) # int|float", "following conditions: # # The above copyright notice and this permission notice shall", "----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs)", "currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static", "a date encoded field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode:", "execute_queries: db_cursor.execute(query) # Done processing - update user if print_progress: print(\" - Done\")", "Postgres formatted database connection string :type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table:", "[--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres supported connection string. All other", "process_subsample = None process_subsample_min = 0 # User feedback settings print_progress = True", "1234 is being processed, the bare minimum field map example below states that", "not an existing destination should be overwritten :type overwrite: bool :return: path to", "*/# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp to a", "print(\"ERROR: Could not connect to database: %s\" % db_connection_string) print(\" Postgres Error: %s\"", "======================================================================= */# #/* Python setup #/* ======================================================================= */# if sys.version[0] is 2: range", "args[i - 1] elif arg == '--db-user': i += 2 db_user = args[i", "'--db-host': i += 2 db_host = args[i - 1] elif arg == '--db-user':", "\"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/* Define print_help_info()", "else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode,", "column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the ordered column", "*/# def column_names(sheet, formatter=str): \"\"\" Get the ordered column names from an XLRD", "NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in the NRC", "*/# #/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ]", "to the target directory if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need", "} ] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return:", "ALL inserts - tell parent process there's nothing left to do return initial_value_to_be_returned", "NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "\"\"\" Print out license information :return: 1 for exit code purposes :rtype: int", "%s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if", "@staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/*", "'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\"", "psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python setup #/* =======================================================================", "arguments from the commandline (sys.argv[1:] in order to drop the script name) :type", "is roughly as follows: All field maps = { 'table_name': [ { 'db_table':", "field_map.keys()]) indent = \" \" * 2 print(\"Initial row counts:\") for schema_table, count", "around the target field. There should be one map for every field in", "'\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, {", "describe which fields in which sheets should be inserted into which table in", "db_row_count(db_cursor, ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/*", "{ 'Column1': 'Row 2 Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even more", "{ 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name':", "into a list of rows, each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\"", "Name of target field, 'db_field_width': Maximum width for this field - used in", "*/# class BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet do not map", "1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get", "'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS':", "out license information :return: 1 for exit code purposes :rtype: int \"\"\" print(__license__)", "db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx'", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "--no-download Don't download the input file --overwrite-download If the --file-to-process already exists and", "#/* Add this field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #", "to schema.table db_cursor The cursor to be used for all queries db_null_value Value", "the default file name containing datetime down to the second. --file-to-process Specify where", "parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */# # Database -", "print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError,", "======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not", "to downloaded file :rtype: str|unicode \"\"\" # Validate arguments if not overwrite and", "field map shows that no specific column contains the value required for public.\"NrcParsedReport\".longitude", "a matching row if row[sheet_seqnos_field] == uid: # The first instance goes into", "not queries should be printed as they are executed raw_sheet_cache Structured similar to", "quotes around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema':", "None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object):", "\", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception as e:", "int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid subsample or subsample min -", "False # Additional options elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file =", "file_to_process)) # Make sure the user has write permission to the target directory", "+= 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() #", "} }, { 'db_table': Name of target table, 'db_field': Name of target field,", "# \"\"\" Scraper for the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name", "name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for permanent archival :param input_name: input", "the sheet to test if map_def['sheet_name'] is not None and map_def['column'] is not", ":param seqnos: reportnum :type seqnos: int|float :param field: :type field: :return: :rtype: bool", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "as workbook: # Establish a DB connection and turn on dict reading db_conn", "'Row 3 Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even more Row 3", "modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to", "download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the user has", "xlrd #/* ======================================================================= */# #/* Python setup #/* ======================================================================= */# if sys.version[0] is", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments map_def =", "raw_sheet_cache Structured similar to the normal sheet cache, but with a list of", "= kwargs['sheet_cache'] # TODO: This currently only reads rows from the sheet specified", "db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure", "to be excluded from the insert statement for that table. { 'db_table': '\"NrcParsedReport\"',", "'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output =", "This catches three conditions: # 1. The last argument is a flag that", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width':", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "sheet - populate a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/*", "'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table':", "object into a list of rows, each structured as a dictionary Example Input:", "file name containing datetime down to the second. --file-to-process Specify where the input", "being processed (example below) print_queries Specifies whether or not queries should be printed", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing':", "#/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx name for permanent", ":rtype: str|unicode \"\"\" # Validate arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR:", "the user did not supply the parameter # 2. The arg parser did", "*/# # Cache all sheets needed by the field definitions as dictionaries print(\"Caching", "0 on success and 1 on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */#", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] } }", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, {", "# Make sure arguments were properly parse if arg_error: bail = True print(\"ERROR:", "elif arg in ('--license', '-usage'): return print_license() # Spreadsheet I/O elif arg ==", ":type seqnos: int|float :param field: :type field: :return: :rtype: bool \"\"\" reportnum =", "[] extra_query_values = [] # Found a matching row if row[sheet_seqnos_field] == uid:", "so this is more of a safety net if value is None or", "to database: %s\" % db_connection_string) print(\" Postgres Error: %s\" % e) return 1", "(%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try:", "raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] #", "The structure for field maps is roughly as follows: All field maps =", "{ 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing':", "Encountered an error validating the field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1", "'\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id", "{ 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, {", "(c) 2014 SkyTruth # # Permission is hereby granted, free of charge, to", "print_version() function #/* ======================================================================= */# def print_version(): \"\"\" Print script version information :return:", "*/# #/* Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\"", "ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower() not in ('n', 'e', 's',", "\"\"\" Scraper for the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth", "* len(__docname__))) return 1 #/* ======================================================================= */# #/* Define print_license() function #/* =======================================================================", "#/* ----------------------------------------------------------------------- */# # Database db_connection_string = None db_host = 'localhost' db_name =", "user to overwrite the default credentials and settings if db_connection_string is None: db_connection_string", "2-4 until all tables have been processed Example bare minimum field map: The", "# NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep +", "max([len(i) for i in field_map.keys()]) indent = \" \" * 2 print(\"Initial row", "======================================================================= */# #/* Build information #/* ======================================================================= */# __version__ = '0.1-dev' __release__ =", "success and 1 on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define", "in unique_report_ids: # Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \"", "execute_queries Specifies whether or not queries should actually be executed map_def Current map", "safety net if value is None or not value: value = db_null_value #", "'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema':", "map for every field in a table. The structure for field maps is", "workbook: :param row: :type row: :param map_def: :type map_def: :rtype: :return: \"\"\" #", "\"\"\" Some fields in the NRC spreadsheet do not map directly to a", "'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public',", "in the field map and NOT the extra field maps # specified in", "a copy of this software and associated documentation files (the \"Software\"), to deal", "'<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ = ''' The MIT License", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees':", "xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB connection and turn on dict", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "something better. # Perhpas have a report_exists method on each of the field", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the", "----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require the", "Postgres supported timestamp format. This method eliminates repitition :param workbook: :type workbook: :param", "and to permit persons to whom the Software is furnished to do so,", "- specified in the field map arguments for e_db_map in extras_field_maps: for e_map_def", "processing happens. Field maps using additional processing always receive the following kwargs: all_field_maps", "extra field maps # specified in the processing args. Currently not a problem", "{1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries]", "--db-host localhost \"\"\" from __future__ import division from __future__ import print_function from __future__", "= row[map_def['processing']['args']['unit_field']] # If the value is not a float, change it to", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None },", "Build query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values", "#/* ======================================================================= */# def print_license(): \"\"\" Print out license information :return: 1 for", "of SEQNOS/reportnum's are gathered from one of the workbook's sheets. The default column", "method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row", "'Even More Row 1 Values' }, { 'Column1': 'Row 2 Val', 'Column2': 'Another", "----------------------------------------------------------------------- */# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\"", "specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table", "statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id", "row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] # Found a matching", "list(set(unique_report_ids)) # Grab a subsample if necessary if process_subsample is not None and", "'Column3': 'Even more Row 2 Values' } { 'Column1': 'Row 3 Val', 'Column2':", "FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */#", "_sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "% (schema, table, field, reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/*", "seqnos: int|float :param field: :type field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum']", "= psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate", "XLRD workbook object The callable object specified in map_def['processing']['function'] is responsible for ALL", "workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict", "report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see if a", "containing \"1.23 METERS\" # This function takes care of that but must still", "'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS',", "'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public',", "password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres supported", "= map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries,", "'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None", "#/* ======================================================================= */# def main(args): \"\"\" Main routine to parse, transform, and insert", "row[map_def['column']] if value == 'INC': value = 'INCIDENT' return value #/* ======================================================================= */#", "of elements, each containing one row of the sheet as a dictionary :rtype:", "'.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing", "nothing to do if value == '' or unit == '': return db_null_value", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG',", "where the input file will be downloaded to If used in conjunction with", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* -----------------------------------------------------------------------", "returned at the very end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] #", "[ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing':", "# Make sure the user has write permission to the target directory if", "parse arguments\") # Make sure the downloaded file is not going to be", ":type schema_table: str|unicode :return: number of rows in the specified schema.table :rtype: int", "not get the sheet to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet", "schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding", "# Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } } ], } The", "Loops: # Get a report number to process # Get a set of", "map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source: %s ->", "dictionary containing reportnums as keys and rows as values row The current row", "Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */#", "in order to drop the script name) :type args: list :return: 0 on", "at the very end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL", "but this behavior is not required. If the function itself handles all queries", "Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/*", "part of the SQL statement for writes (e.g. INSERT INTO) execute_queries Specifies whether", "map_def: :rtype: :return: \"\"\" # TODO: Use 24 hour time workbook = kwargs['workbook']", "as keys and rows as values row The current row being processed -", "None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema':", "= {row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError: # Sheet was empty", "'Arg2': ... } } }, ], 'TABLE_NAME': [ { 'db_table': Name of target", "== '--subsample': i += 2 process_subsample = args[i - 1] elif arg ==", "list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */# #/* Define", "'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public',", "# db_conn.commit() # connection is now set to autocommit db_cursor.close() db_conn.close() return 0", "row The current row being processed - structured just like a csv.DictReader row", "# Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps", "the same existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s", "column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "#/* ----------------------------------------------------------------------- */# #/* Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "1 Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another Row", "destination: str|unicode :param overwrite: specify whether or not an existing destination should be", "These fields require an additional processing step that is highly specific and cannot", "execute_queries = False # Additional options elif arg == '--overwrite-download': i += 1", "kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps']", "args[i - 1] elif arg == '--db-pass': i += 2 db_pass = args[i", "did not properly iterate the 'i' variable except IndexError: i += 1 arg_error", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"',", "queries db_null_value Value to use for NULL db_seqnos_field The reportnum field in the", "Help arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg", "function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function called", "#/* Define print_version() function #/* ======================================================================= */# def print_version(): \"\"\" Print script version", "string slicing 'db_schema': Name of target schema, 'sheet_name': Name of source sheet in", "int(degrees) + int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower() in ('s',", "to # have the same existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT", "we don't have to # have the same existance test for all tables", "= args[i - 1] elif arg == '--db-name': i += 2 db_name =", "in which schema. Each field map is applied against each ID which means", "supply the expected post-normalization format if unit.upper() not in multipliers: return db_null_value return", "for the \"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami`", "= dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return output", "row since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols)))", "----------------------------------------------------------------------- */# # Database - must be done here in order to allow", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "[ { 'db_table': Name of target table, 'db_field': Name of target field, 'db_field_width':", "for the target database [default: localhost] --db-user Username used for database connection [default:", "executed map_def Current map definition being processed (example below) print_queries Specifies whether or", "any person obtaining a copy of this software and associated documentation files (the", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } }, { # TODO:", "True print(\"ERROR: An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options", "sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements,", "'MILES': 5280, 'NI': 5280, # Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed", "query to console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done processing", "#/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook =", "a file :param url: URL to download from :type url: str|unicode :param destination:", "'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum',", "additional sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } }", "Repeat steps 2-4 until all tables have been processed Example bare minimum field", "#/* Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field", "from which to download the input file --no-download Don't download the input file", "= db_null_value # Pass all necessary information to the processing function in order", "in ('--version', '-version'): return print_version() elif arg in ('--license', '-usage'): return print_license() #", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"',", "import psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python setup #/* ======================================================================= */#", "5. Repeat steps 2-4 until all tables have been processed Example bare minimum", "True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map definitions #/*", "Sheet was empty pass # Get a list of unique report id's unique_report_ids", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause',", "'-help-info'): return print_help_info() elif arg in ('--help', '-help', '--h', '-h'): return print_help() elif", "to process # Get a field map to process print(\"Processing workbook ...\") num_ids", "% (indent, schema_table + ' ' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table]", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None", "not been specified, blindly overwrite the file. Unless the user is specifying a", "======================================================================= */# #/* Define print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\" Command", "1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options]", "= db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single field", "# Get a report number to process # Get a set of field", "= True print(\"ERROR: Invalid subsample or subsample min - must be an int:", "function #/* ======================================================================= */# def print_help(): \"\"\" Detailed help information :return: 1 for", "'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i = 0", "'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "if print_queries: print(\"\") try: print(query) except Exception as e: print (\"Error printing SQL", "'w'): output *= -1 return output #/* ======================================================================= */# #/* Define column_names() function", "list of column names :rtype: list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)]", "#/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field':", "# Additional options elif arg == '--overwrite-download': i += 1 overwrite_downloaded_file = True", "The last argument is a flag that requires parameters but the user did", "= \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0])", "(MIT) Copyright (c) 2014 SkyTruth Permission is hereby granted, free of charge, to", "# This function takes care of that but must still supply the expected", "32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\",", "row[map_def['column']] # ALL occurrences are sent to a different table - specified in", "None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"',", "\"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method", "process the reportnum information since it was added to the initial query above", "the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output #/* =======================================================================", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None", "'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments from the commandline", "time_stamp(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/*", "do so, subject to the following conditions: The above copyright notice and this", "to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static method", "db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is properly quoted", "psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python setup #/* ======================================================================= */# if", "doing any transformations, a set of SEQNOS/reportnum's are gathered from one of the", "'\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id", "the quotes around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32,", "\"\"\" See documentation for function called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs)", "like a csv.DictReader row sheet The entire sheet from which the row was", "in order to allow the user to overwrite the default credentials and settings", "#/* ======================================================================= */# #/* Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\"", "not None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail =", "description of this utility --usage Arguments, parameters, flags, options, etc. --version Version and", "#/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\"", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if the report already exists", "''] --download-url URL from which to download the input file --no-download Don't download", "an additional processing step that is highly specific and cannot be re-used. The", "dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache = {} for sname in", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "# Commandline print-outs elif arg == '--no-print-progress': i += 1 print_progress = False", "'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema':", "'\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, {", "(example below) print_queries Specifies whether or not queries should be printed as they", "if arg_error: bail = True print(\"ERROR: Did not successfully parse arguments\") # Make", "with all options: This field map shows that no specific column contains the", "print(\"ERROR: Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure", ":param input_name: input file name (e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted", "not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download target exists:", "*/# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return", ":param formatter: :type formatter: type|function :return: list of column names :rtype: list \"\"\"", ":param destination: target path and filename for downloaded file :type destination: str|unicode :param", "*/# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\"", "dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* -----------------------------------------------------------------------", "column names from an XLRD sheet object :param sheet: XLRD sheet object :type", "*/# # Database - must be done here in order to allow the", "transform, and insert Current.xlsx into the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx", "\" * 2 print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" %", "containing datetime down to the second. --file-to-process Specify where the input file will", "'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args:", "a list of unique report id's unique_report_ids = [] for s_name, s_rows in", "by the parent process so this value is # returned at the very", "# Do something with the query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\"", "workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/* ======================================================================= */#", "specific values if isinstance(value, str) or isinstance(value, unicode): # Having single quotes in", "final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding - len(schema_table) +", "print(\"ERROR: Can't find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could", "# The above copyright notice and this permission notice shall be included in", "db_cursor The cursor to be used for all queries db_null_value Value to use", "# of this software and associated documentation files (the \"Software\"), to deal #", "# Found a sheen size and unit - perform conversion else: multipliers =", "additional processing always receive the following kwargs: all_field_maps All field maps with keys", "= None db_host = 'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass =", "None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public',", "additional processing is required, simply grab the value from the sheet and add", "'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema':", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method #/* -----------------------------------------------------------------------", "'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS',", "\"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values))", "url: URL to download from :type url: str|unicode :param destination: target path and", "= True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field']))", "to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i = 0 # Loop", "'%s' AND table_name = '%s' AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"',", "Check to see if a report has already been submitted to a table", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "for processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB: %s\" %", "[--overwrite] Options: --db-connection-string Explicitly define a Postgres supported connection string. All other --db-*", "The arg parser did not properly iterate the 'i' variable except IndexError: i", "coordinate degrees :type degrees: int :param minutes: coordinate minutes :type minutes: int :param", "check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public',", "did not supply the parameter # 2. The arg parser did not properly", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema':", "kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static method #/* -----------------------------------------------------------------------", "an XLRD sheet object :param sheet: XLRD sheet object :type sheet: xlrd.Sheet :param", "in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] # Found a matching row", "DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static method #/*", "column_names(sheet) for r in range(1, sheet.nrows): # Skip first row since it contains", "'\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None", "except KeyError: # UID doesn't appear in the specified sheet - populate a", "'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { #", "validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'],", ":type input_name: str|unicode :return: output formatted name :rtype: str|unicode \"\"\" dt = datetime.now()", "sent to a different table - specified in the field map arguments for", "field. There should be one map for every field in a table. The", "(c) 2014 SkyTruth Permission is hereby granted, free of charge, to any person", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a", "nothing so the next test fails try: value = float(value) except ValueError: value", "in string slicing 'db_schema': Name of target schema, 'sheet_name': Name of source sheet", "User feedback settings print_progress = True print_queries = False execute_queries = True final_table_counts", "if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help',", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "field map classes so we don't have to # have the same existance", "= False while i < len(args): try: arg = args[i] # Help arguments", "output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static method", "kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: # UID", "== 'INC': value = 'INCIDENT' return value #/* ======================================================================= */# #/* Define NrcParsedReportFields()", "without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "*/# def print_usage(): \"\"\" Command line usage information :return: 1 for exit code", "list of elements, each containing one row of the sheet as a dictionary", "code purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' *", "row = kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit", "is expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if", "= xrange #/* ======================================================================= */# #/* Build information #/* ======================================================================= */# __version__ =", "an insert query 4. Execute the insert statement 5. Repeat steps 2-4 until", "reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\" % (schema, table,", "dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return output #/*", "against each ID which means that if ID number 1234 is being processed,", "fields in which sheets should be inserted into which table in which schema.", "set of ID's are treated as primary keys and drive processing. Rather than", "% e) return 1 # Prep workbook print(\"Opening workbook: %s\" % file_to_process) with", "'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name':", "table for db_map in field_map_order: query_fields = [] query_values = [] # If", "----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs):", "of this software and associated documentation files (the \"Software\"), to deal # in", "Current.xlsx into the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any", "kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently only reads rows from the", "return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method #/* ----------------------------------------------------------------------- */#", "print_queries = False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* -----------------------------------------------------------------------", "follows: All field maps = { 'table_name': [ { 'db_table': Name of target", "exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the user has write permission", "#/* ======================================================================= */# #/* Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\"", "get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet,", "require the same general logic. \"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees']", "sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into a list of rows, each", ":param seconds: coordinate seconds :type seconds: int :param quadrant: coordinate quadrant (N, E,", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static method #/* ----------------------------------------------------------------------- */#", "'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "in conjunction with --no-download it is assumed that the specified file already exists", "----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function called in the", "and destroy DB connections # db_conn.commit() # connection is now set to autocommit", "*/# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function called in the return", "person obtaining a copy # of this software and associated documentation files (the", "'\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, {", "maps with keys set to schema.table db_cursor The cursor to be used for", "in ('--license', '-usage'): return print_license() # Spreadsheet I/O elif arg == '--no-download': i", "range(1, sheet.nrows): # Skip first row since it contains the header output.append(dict((columns[c], sheet.cell_value(r,", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "field maps for a single table to process # Get a field map", "should actually be executed map_def Current map definition being processed (example below) print_queries", "+ ' ' * (padding - len(schema_table) + 4), count)) print(\"New rows:\") for", "is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The", "kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is None: try: value = row[map_def['column']] except", "Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid =", "'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table':", "len(unique_report_ids) uid_i = 0 # Loop through the primary keys for uid in", "class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet", "persons to whom the Software is # furnished to do so, subject to", "Get a set of field maps for one target table 3. Process all", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "@staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs)", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "ft_id(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/*", "Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\" Example Output:", "very end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are", "uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush()", "field containing \"1.23 METERS\" # This function takes care of that but must", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing':", "download the input file --no-download Don't download the input file --overwrite-download If the", "been submitted to a table :param seqnos: reportnum :type seqnos: int|float :param field:", "Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username]", "db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field", "e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row,", "Test connection print(\"Connecting to DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close()", "seconds :type seconds: int :param quadrant: coordinate quadrant (N, E, S, W) :type", "# Spreadsheet I/O elif arg == '--no-download': i += 1 download_file = False", "'\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, {", "print_usage(): \"\"\" Command line usage information :return: 1 for exit code purposes :rtype:", "= kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static method #/*", "'\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, {", "or subsample min - must be an int: %s\" % process_subsample) # Exit", ":type workbook_datemode: int :return: date capable of being inserted into Postgres timestamp field", "*/# #/* Process data #/* ----------------------------------------------------------------------- */# # Loops: # Get a report", "a flag that requires parameters but the user did not supply the parameter", "db_user = args[i - 1] elif arg == '--db-name': i += 2 db_name", "if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String", "'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "% (overwrite, destination)) # Download response = urllib2.urlopen(url) with open(destination, 'w') as f:", "this field - used in string slicing 'db_schema': Name of target schema, 'sheet_name':", "name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static", ":param schema_table: schema.table :type schema_table: str|unicode :return: number of rows in the specified", "NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "Name of target schema, 'sheet_name': Name of source sheet in input file, 'column':", "*/# #/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\"", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD workbook for processing", ":return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help", "to be used for all queries db_null_value Value to use for NULL db_seqnos_field", "unique_report_ids = [i for i in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids", "sheet cache, but with a list of rows instead of a dictionary containing", "schema = kwargs['schema'] # TODO: replace this hack with something better. # Perhpas", "{} for sname in workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict =", "file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value", "'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id }", "object The callable object specified in map_def['processing']['function'] is responsible for ALL queries. The", "#/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [", "field maps is roughly as follows: All field maps = { 'table_name': [", "from a field containing \"1.23 METERS\" # This function takes care of that", "in the string causes problems on insert because the entire # value is", "db_map in field_map_order: query_fields = [] query_values = [] # If the report", "and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite, destination)) #", "NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC", "#/* Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor:", "kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This", "whether or not an existing destination should be overwritten :type overwrite: bool :return:", "notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name':", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "sure arguments were properly parse if arg_error: bail = True print(\"ERROR: Did not", "----------------------------------------------------------------------- */# #/* Cache initial DB row counts for final stat printing #/*", "return print_usage() elif arg in ('--version', '-version'): return print_version() elif arg in ('--license',", "True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/*", "======================================================================= */# if sys.version[0] is 2: range = xrange #/* ======================================================================= */# #/*", "# # =================================================================================== # \"\"\" Scraper for the \"temporary\" NRC incident spreadsheet Sample", "and settings if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" %", "\".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception as e: print (\"Error printing", "'-h'): return print_help() elif arg in ('--usage', '-usage'): return print_usage() elif arg in", "None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "in the NRC spreadsheet do not map directly to a column in the", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "object :type sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return: list of column", "count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table +", "----------------------------------------------------------------------- */# #/* Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs):", "unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if necessary if process_subsample is", "= kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output =", "not supply the parameter # 2. The arg parser did not properly consume", "overwrite_downloaded_file = False download_file = True process_subsample = None process_subsample_min = 0 #", "name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static", "} The order of operations for a given ID is as follows: 1.", "= [] for s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids", "functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method", ":return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" %s version %s", "material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries']", "'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32,", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None },", "'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, }", "protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and", "'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3 } # Database is", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH',", "scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License (MIT) #", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "Currently not a problem since # Build query initial_value_to_be_returned = None for row", "def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row =", "the parent process so this value is # returned at the very end", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "or isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single quotes cause problems on", "error validating the field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* -----------------------------------------------------------------------", "as a dictionary :rtype: dict \"\"\" output = [] columns = column_names(sheet) for", "allow the user to overwrite the default credentials and settings if db_connection_string is", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes':", "specify whether or not an existing destination should be overwritten :type overwrite: bool", "{ 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "by the field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache", "NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly to", "{0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */#", "#/* ----------------------------------------------------------------------- */# #/* Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "except KeyError: row = None # If no additional processing is required, simply", "not queries should actually be executed map_def Current map definition being processed (example", "decimal degrees :rtype: float \"\"\" illegal_vals = (None, '', u'') for iv in", "- must be done here in order to allow the user to overwrite", "a sheen size and unit - perform conversion else: multipliers = { 'F':", "ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite, destination)) # Download response =", "formatter=str): \"\"\" Get the ordered column names from an XLRD sheet object :param", "# int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the query query = \"\"\"%s", "3 Val', 'Column3': 'Even more Row 3 Values' } ] :param sheet: XLRD", "free of charge, to any person obtaining a copy # of this software", "list of rows, each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1", "extra_query_fields = [] extra_query_values = [] # Found a matching row if row[sheet_seqnos_field]", "'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema':", "URLLIB Error: %s\" % e) return 1 # Prep workbook print(\"Opening workbook: %s\"", "containing one row of the sheet as a dictionary :rtype: dict \"\"\" output", "for database connection [default: current user] --db-name Name of target database [default: skytruth]", "len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/* Define print_help_info() function #/* =======================================================================", "value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method #/*", "----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs):", "' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */#", "- perform conversion else: multipliers = { 'F': 1, 'FE': 1, 'FEET': 1,", "bail = True print(\"ERROR: Invalid subsample or subsample min - must be an", "download(url, destination, overwrite=False): \"\"\" Download a file :param url: URL to download from", "reading from a field containing \"1.23 METERS\" # This function takes care of", "for the download, this flag is not needed due the default file name", "+= 2 download_url = args[i - 1] elif arg == '--file-to-process': i +=", "= process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries,", "version %s - released %s \"\"\" % (__docname__, __version__, __release__)) return 1 #/*", "sheet from which the row was extracted as described in the field map", "Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output Current.xlsx", "for i in field_map.keys()]) indent = \" \" * 2 print(\"Initial row counts:\")", "try: print(query) except Exception as e: print (\"Error printing SQL query to console", "like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static method #/* -----------------------------------------------------------------------", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting", "Parse arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error = False while i", "This method eliminates repitition :param workbook: :type workbook: :param row: :type row: :param", "the next test fails try: value = float(value) except ValueError: value = ''", "'\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude,", "print_version() elif arg in ('--license', '-usage'): return print_license() # Spreadsheet I/O elif arg", "of a dictionary containing reportnums as keys and rows as values row The", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name':", "value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object):", "the string causes problems on insert because the entire # value is single", "Execute the insert statement 5. Repeat steps 2-4 until all tables have been", "Software, and to permit persons to whom the Software is # furnished to", "[] query_values = [] # If the report already exists, in the target", "print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding - len(schema_table) + 4),", "TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/*", "= ''' The MIT License (MIT) Copyright (c) 2014 SkyTruth Permission is hereby", "%s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating the", "db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB row counts", "#/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement - currently returning NULL", "report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single field map to process for", "%I:%M:%S'): \"\"\" Convert a float formatted date a Postgres supported timestamp :param stamp:", "return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */#", "workbook's sheets. The default column in 'CALLS' but can be specified by the", "is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass)", "sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that a specific function", "#/* ----------------------------------------------------------------------- */# #/* Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "if ID number 1234 is being processed, the bare minimum field map example", "in order to be excluded from the insert statement for that table. {", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "Example bare minimum field map: The field map below shows that the value", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None", "around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public',", "for sname in workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname))", "execute one of these processing functions. A class is used as a namespace", "expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if value", "try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR:", ":param args: arguments from the commandline (sys.argv[1:] in order to drop the script", "value extra_query_fields.append(e_map_def['db_field']) # Do something with the query query = \"\"\"%s %s.%s (%s)", "None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict} except", "methods require the same general logic. \"\"\" try: row = kwargs['row'] col_deg =", "{ 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width',", "unicode_literals from datetime import datetime import getpass import os from os.path import *", "----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping ...\") for db_map in field_map_order:", "# Skip first row since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for", "'Another Row 3 Val', 'Column3': 'Even more Row 3 Values' } ] :param", "connection print(\"Connecting to DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except", "around specific values if isinstance(value, str) or isinstance(value, unicode): # Having single quotes", "size - nothing to do if value == '' or unit == '':", "} } }, :param args: arguments from the commandline (sys.argv[1:] in order to", "Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\" Example Output: [ { 'Column1':", "Download a file :param url: URL to download from :type url: str|unicode :param", "+= 2 db_connection_string = args[i - 1] elif arg == '--db-host': i +=", "is assumed that the specified file already exists and should be used for", "arguments\") # Make sure the downloaded file is not going to be accidentally", "a column in the database. These fields require an additional processing step that", "'Column1': 'Row 1 Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even More Row", "'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL',", "coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define", "4. Execute the insert statement 5. Repeat steps 2-4 until all tables have", "*/# #/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string = None db_host", "'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table':", "with --no-download it is assumed that the specified file already exists and should", "end if initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "of target field, 'db_schema': Name of target schema, 'sheet_name': Name of source sheet", "following conditions: The above copyright notice and this permission notice shall be included", "stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "#/* Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert", "'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name',", "== '--overwrite-download': i += 1 overwrite_downloaded_file = True elif arg == '--subsample': i", "due the default file name containing datetime down to the second. --file-to-process Specify", "and/or sell # copies of the Software, and to permit persons to whom", "states that a specific function must do more of the heavy lifting. Field", "in the set of mappings for map_def in field_map[db_map]: # Attempt to get", "\"\"\" Check to see if a report has already been submitted to a", "db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail", "which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "for row in sheet_dict} except IndexError: # Sheet was empty pass # Get", "flag is not needed due the default file name containing datetime down to", "sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated", "\"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/* -----------------------------------------------------------------------", "database db_write_mode The first part of the SQL statement for writes (e.g. INSERT", "as e: print (\"Error printing SQL query to console (unicode weirdness?\") print (e.message)", "field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"',", "'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table':", "True print(\"ERROR: Invalid argument: %s\" % arg) # This catches three conditions: #", "isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single quotes cause problems on insert", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "= row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value is not a float,", "purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help More detailed description of this", "@staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function called in the return statement", "db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB row counts for", "\"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt", "kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/* ======================================================================= */# class", "'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name':", "which table in which schema. Each field map is applied against each ID", "There should be one map for every field in a table. The structure", "{ 'function': NrcParsedReportFields.areaid } }, { # TODO: Implement - check notes about", "--help More detailed description of this utility --usage Arguments, parameters, flags, options, etc.", "'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file =", "# Validate arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile", "get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']],", "repitition :param workbook: :type workbook: :param row: :type row: :param map_def: :type map_def:", "parser did not properly consume all parameters for an argument # 3. The", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement - currently", "about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "the database. These fields require an additional processing step that is highly specific", "information_schema.columns WHERE table_schema = '%s' AND table_name = '%s' AND column_name = '%s';\"", "all of the additional arguments and information necessary to execute one of these", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "structured just like a csv.DictReader row sheet The entire sheet from which the", "Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for", "NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/*", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */#", "{ 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id',", "and/or sell copies of the Software, and to permit persons to whom the", "path to downloaded file :rtype: str|unicode \"\"\" # Validate arguments if not overwrite", "arg == '--no-print-progress': i += 1 print_progress = False elif arg == '--print-queries':", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query) except Exception as", ":param minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds :type seconds:", "NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\")", "print(\" Postgres Error: %s\" % e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download", "-> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the sheet to", "(%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries:", "{ 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name':", "os.path import * import sys import urllib2 import psycopg2 import psycopg2.extras import xlrd", "DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value = row[map_def['column']] except", "} } }, { # TODO: Implement - check notes about which column", "do so, subject to the following conditions: # # The above copyright notice", "query_values = [str(uid)] else: # Get the row for this sheet try: row", "table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema,", "function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the ordered column names", "#/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB: %s\" % db_connection_string) try:", "def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */#", "extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def,", "= float(value) except ValueError: value = '' # No sheen size - nothing", "will be downloaded to If used in conjunction with --no-download it is assumed", "= \" \" * 2 print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems():", "schema_table + ' ' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table]))", "2 file_to_process = abspath(args[i - 1]) # Database connection elif arg == '--db-connection-string':", "on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/*", "destination: target path and filename for downloaded file :type destination: str|unicode :param overwrite:", "'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { #", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "field maps = { 'table_name': [ { 'db_table': Name of target table, 'db_field':", "be inserted into the target field described in the field map but this", "return output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static method #/* ----------------------------------------------------------------------- */#", "bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field =", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "arg_error: bail = True print(\"ERROR: Did not successfully parse arguments\") # Make sure", "definitions as dictionaries print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache = {} for", "@staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* -----------------------------------------------------------------------", "'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table':", "sure the user has write permission to the target directory if not os.access(dirname(file_to_process),", "initial_value_to_be_returned is None: initial_value_to_be_returned = row[map_def['column']] # ALL occurrences are sent to a", "the row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row =", "----------------------------------------------------------------------- */# #/* Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs):", "# have the same existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT *", "a report_exists method on each of the field map classes so we don't", "'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } },", "#/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def =", "5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping of 'MI' 'UN': 0.0833333, #", "db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/* ======================================================================= */#", "1] elif arg == '--db-name': i += 2 db_name = args[i - 1]", "db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table':", "The callable object specified in map_def['processing']['function'] is responsible for ALL queries. The processing", "def latitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/*", "======================================================================= */# #/* Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert", "- 1] elif arg == '--file-to-process': i += 2 file_to_process = abspath(args[i -", "kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries']", "target field, 'db_field_width': Maximum width for this field - used in string slicing", "row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + '", "should be printed as they are executed raw_sheet_cache Structured similar to the normal", "int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output *= -1 return output", "NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "some information must be passed to the NrcParsedReportFields.longitude() function where the actual processing", "purposes :rtype: int \"\"\" print(\"\"\" %s version %s - released %s \"\"\" %", "\"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/*", "'column': None, 'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot',", "# Get a set of field maps for a single table to process", "print_help() elif arg in ('--usage', '-usage'): return print_usage() elif arg in ('--version', '-version'):", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ {", "or not value: value = db_null_value # Assemble query if value not in", "raise ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower() not in ('n', 'e',", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: #", "= 'August 8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__)", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing':", "count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding -", "#/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/*", "table exist in the DB query = \"SELECT * FROM information_schema.columns WHERE table_schema", "the normalization by reading from a field containing \"1.23 METERS\" # This function", "simply grab the value from the sheet and add to the query if", "values - these should be handled elsewhere so this is more of a", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table':", "None and process_subsample < len(unique_report_ids): # TODO: Delete constraining line - needed to", "None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema':", "= getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value", "Value to use for NULL db_seqnos_field The reportnum field in the database db_write_mode", "Download response = urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return destination #/*", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None },", "def _datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp to a Postgres supported", "#/* Define column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the", "Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row", "status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static method #/* -----------------------------------------------------------------------", "cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function #/* ======================================================================= */#", "- currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler()", "a single table to process # Get a field map to process print(\"Processing", "----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "results = db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR: Invalid DB target:", "in order to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row,", "ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a", "@staticmethod def platform_letter(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None)", "affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/*", "*/# #/* Define print_help() function #/* ======================================================================= */# def print_help(): \"\"\" Detailed help", "row: :type row: :param map_def: :type map_def: :rtype: :return: \"\"\" # TODO: Use", "process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */# # Loops: #", "'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public',", "of these processing functions. A class is used as a namespace to provide", "*/# #/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): #", "Cleanup and final return #/* ----------------------------------------------------------------------- */# # Update user padding = max([len(i)", "'\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width,", "DEALINGS IN THE # SOFTWARE. # # =================================================================================== # \"\"\" Scraper for the", "If the --file-to-process already exists and --no-download has not been specified, blindly overwrite", "'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table':", "#/* ======================================================================= */# #/* Define print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\"", "value = value.replace(\"'\", '\"') # Single quotes cause problems on insert try: if", "that requires parameters but the user did not supply the parameter # 2.", "and unit - perform conversion else: multipliers = { 'F': 1, 'FE': 1,", "as primary keys and drive processing. Rather than process the input document sheet", "the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "the value required for public.\"NrcParsedReport\".longitude Instead, some information must be passed to the", "the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company", "NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "included in all # copies or substantial portions of the Software. # #", "'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "Row 3 Values' } ] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type", "if quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\"", "kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field']", "db_pass = args[i - 1] # Commandline print-outs elif arg == '--no-print-progress': i", "type|function :return: list of column names :rtype: list \"\"\" return [formatter(cell.value) for cell", "of rows in the specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1)", "'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name':", "workbook for processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB: %s\"", "help related flags :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\"", "[--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options:", "======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download a file :param url: URL", "the function itself handles all queries internally it can return '__NO_QUERY__' in order", "int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the query query = \"\"\"%s %s.%s", "'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps':", "not a float, change it to nothing so the next test fails try:", "output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "Make sure the user has write permission to the target directory if not", "elif arg == '--db-user': i += 2 db_user = args[i - 1] elif", "= map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor =", "information since it was added to the initial query above if map_def['db_field'] ==", "recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function", "parameters #/* ----------------------------------------------------------------------- */# bail = False # Make sure arguments were properly", "'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__ import division from", "i += 2 db_host = args[i - 1] elif arg == '--db-user': i", "= True print(\"ERROR: Did not successfully parse arguments\") # Make sure the downloaded", "ID is as follows: 1. Get an ID 2. Get a set of", "processed, the bare minimum field map example below states that whatever value is", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table':", ":rtype: dict \"\"\" output = [] columns = column_names(sheet) for r in range(1,", "DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static", "for ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table", "def platform_letter(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/*", "if process_subsample is not None and process_subsample < len(unique_report_ids): # TODO: Delete constraining", "'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public',", "was empty pass # Get a list of unique report id's unique_report_ids =", "1] # Commandline print-outs elif arg == '--no-print-progress': i += 1 print_progress =", "'sheet_name': Name of source sheet in input file, 'column': Name of source column", "map states that a specific function must do more of the heavy lifting.", "UID doesn't appear in the specified sheet - populate a NULL value value", "should be overwritten :type overwrite: bool :return: path to downloaded file :rtype: str|unicode", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these should be handled elsewhere so", "import print_function from __future__ import unicode_literals from datetime import datetime import getpass import", "# Pass all necessary information to the processing function in order to get", "like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* -----------------------------------------------------------------------", "= [] columns = column_names(sheet) for r in range(1, sheet.nrows): # Skip first", "value: %s\" % iv) if quadrant.lower() not in ('n', 'e', 's', 'w'): raise", "int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid subsample or", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "%s\" % download_url) print(\" URLLIB Error: %s\" % e) return 1 # Prep", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not populated 'db_table':", "row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value is not a float, change", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "filename for downloaded file :type destination: str|unicode :param overwrite: specify whether or not", "'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments", "= '%s' AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query)", "format if unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) +", "url: str|unicode :param destination: target path and filename for downloaded file :type destination:", "def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date a Postgres", "all tables have been processed Example bare minimum field map: The field map", "AND table_name = '%s' AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''),", "in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help', '-help', '--h',", "'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"',", "\"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec =", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "function #/* ======================================================================= */# def print_license(): \"\"\" Print out license information :return: 1", "[] # If the report already exists, in the target table, skip everything", "#/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see if a report has", "used for all queries db_null_value Value to use for NULL db_seqnos_field The reportnum", "#/* Define print_license() function #/* ======================================================================= */# def print_license(): \"\"\" Print out license", "'--no-download': i += 1 download_file = False elif arg == '--download-url': i +=", "execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to", "ID which means that if ID number 1234 is being processed, the bare", "sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define", "the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function", "Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = {", "# furnished to do so, subject to the following conditions: # # The", "is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file straight", "free of charge, to any person obtaining a copy of this software and", "in field_map_order: # Check each field definition in the set of mappings for", "{ 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name':", "of source sheet in input file, 'column': Name of source column in sheet_name,", "isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single quotes cause", "to test if map_def['sheet_name'] is not None and map_def['column'] is not None: try:", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ], }", "functions are intended to return a final value to be inserted into the", "= int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid subsample or subsample min", "= '0.1-dev' __release__ = 'August 8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper'", "unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/* -----------------------------------------------------------------------", "destroy DB connections # db_conn.commit() # connection is now set to autocommit db_cursor.close()", "= kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/*", "the additional arguments and information necessary to execute one of these processing functions.", "overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download target exists: %s\"", "longitude() methods require the same general logic. \"\"\" try: row = kwargs['row'] col_deg", "was extracted as described in the field map sheet_seqnos_field The field in all", "can be specified by the user. This set of ID's are treated as", "\"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another", "'LONG_QUAD' } } }, :param args: arguments from the commandline (sys.argv[1:] in order", "\"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field',", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None", "Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if the report", "+= 2 process_subsample_min = args[i - 1] # Positional arguments and errors else:", "(e.g. INSERT INTO) execute_queries Specifies whether or not queries should actually be executed", "to drop the script name) :type args: list :return: 0 on success and", "method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement - currently returning", "\"SELECT * FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s' AND", "def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into a list of rows,", "the reportnum information since it was added to the initial query above if", "these should be handled elsewhere so this is more of a safety net", "\"\"\" Generate the output Current.xlsx name for permanent archival :param input_name: input file", "execute_queries: db_cursor.execute(query) # This processing function handled ALL inserts - tell parent process", "#/* ======================================================================= */# def print_help_info(): \"\"\" Print a list of help related flags", "problems on insert because the entire # value is single quoted value =", "any additional processing. Note the quotes around the table name. { 'db_table': '\"NrcScrapedReport\"',", "Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'DESCRIPTION_OF_INCIDENT', 'processing': None },", "#/* ======================================================================= */# #/* Define main() function #/* ======================================================================= */# def main(args): \"\"\"", "str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals = (None, '', u'') for", "coordinate minutes :type minutes: int :param seconds: coordinate seconds :type seconds: int :param", "= False elif arg == '--no-execute-queries': i += 1 execute_queries = False #", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError:", "#/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is", "'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError:", "function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def", "*/# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require the same", "The arg parser did not properly consume all parameters for an argument #", "counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table, count", "map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function", "except ValueError: bail = True print(\"ERROR: Invalid subsample or subsample min - must", "col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except", "printing SQL query to console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) #", "insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these should be", "not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error =", "row being processed - structured just like a csv.DictReader row sheet The entire", "args[i] # Help arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info()", "'\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter", "parser did not properly iterate the 'i' variable except IndexError: i += 1", "function called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/*", "'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter }", "%s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the sheet to test", "False elif arg == '--print-queries': i += 1 print_queries = True print_progress =", "query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query", "} } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "*/# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process) try: download(download_url,", "#/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"',", "print-outs elif arg == '--no-print-progress': i += 1 print_progress = False elif arg", "queries should actually be executed map_def Current map definition being processed (example below)", "is not None and process_subsample < len(unique_report_ids): # TODO: Delete constraining line -", "int|float :param field: :type field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor", "target field, 'db_schema': Name of target schema, 'sheet_name': Name of source sheet in", "i += 2 db_user = args[i - 1] elif arg == '--db-name': i", "are gathered from one of the workbook's sheets. The default column in 'CALLS'", "'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp',", "sheets needed by the field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache =", "and this permission notice shall be included in all # copies or substantial", "= True process_subsample = None process_subsample_min = 0 # User feedback settings print_progress", "Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates", "# Permission is hereby granted, free of charge, to any person obtaining a", "'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "cursor: Postgres formatted database connection string :type cursor: psycopg2.cursor :param schema_table: schema.table :type", "a dictionary containing reportnums as keys and rows as values row The current", "'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id',", "and outfile exists: %s\" % (overwrite, destination)) # Download response = urllib2.urlopen(url) with", "execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse", "print(\"\") try: print(query) except Exception as e: print (\"Error printing SQL query to", "Database is expecting to handle the normalization by reading from a field containing", "table to process # Get a field map to process print(\"Processing workbook ...\")", "add to the query if row is not None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/*", "(db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries:", "dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to decimal degrees", "Get the row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"',", "======================================================================= */# #/* Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check", "information :return: 1 for exit code purposes :rtype: int \"\"\" print(__license__) return 1", "initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define", "'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS',", "user has write permission to the target directory if not os.access(dirname(file_to_process), os.W_OK): bail", "report already exists, in the target table, skip everything else _schema, _table =", "map_def['column'])) # Could not get the sheet to test except xlrd.XLRDError: validate_field_map_error =", "is None: try: value = row[map_def['column']] except KeyError: # UID doesn't appear in", "Specifies whether or not queries should actually be executed map_def Current map definition", "connection and XLRD workbook for processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting", "#/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value',", "col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min],", "#/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string =", "to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/*", "dirname(file_to_process)) # Handle subsample if process_subsample is not None: try: process_subsample = int(process_subsample)", "# Only put quotes around specific values if isinstance(value, str) or isinstance(value, unicode):", "date encoded field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this field map to the insert statement #/*", "_schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a", "db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map", "= column_names(sheet) for r in range(1, sheet.nrows): # Skip first row since it", "% (uid_i, num_ids)) sys.stdout.flush() # Get field maps for one table for db_map", "None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error = True", "arg == '--db-connection-string': i += 2 db_connection_string = args[i - 1] elif arg", "'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement", "user if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final", "subsample if process_subsample is not None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min)", "(e.message) if execute_queries: db_cursor.execute(query) # Done processing - update user if print_progress: print(\"", "'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public',", "= None # If no additional processing is required, simply grab the value", "method eliminates repitition :param workbook: :type workbook: :param row: :type row: :param map_def:", "--db-name Name of target database [default: skytruth] --db-pass Password for database user [default:", "# connection is now set to autocommit db_cursor.close() db_conn.close() return 0 #/* =======================================================================", "bail = True print(\"ERROR: Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file, file_to_process))", "= kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries =", "TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL',", "states that whatever value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be", "appear in the specified sheet - populate a NULL value value = db_null_value", "arguments for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid,", "coordinate quadrant (N, E, S, W) :type quadrant: str|unicode :return: decimal degrees :rtype:", "output = int(degrees) + int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower()", "except ValueError: value = '' # No sheen size - nothing to do", "degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type degrees:", "sell copies of the Software, and to permit persons to whom the Software", "== '' or unit == '': return db_null_value # Found a sheen size", "----------------------------------------------------------------------- */# #/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"'", "'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } },", "output #/* ======================================================================= */# #/* Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs):", "and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download target exists: %s\" %", "This function takes care of that but must still supply the expected post-normalization", "in field_map_order: query_fields = [] query_values = [] # If the report already", "a copy # of this software and associated documentation files (the \"Software\"), to", "\"\"\" print(\"\"\" %s version %s - released %s \"\"\" % (__docname__, __version__, __release__))", "range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define report_exists() function #/* ======================================================================= */#", "all_field_maps All field maps with keys set to schema.table db_cursor The cursor to", "all necessary information to the processing function in order to get a result", "(the \"Software\"), to deal # in the Software without restriction, including without limitation", "'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table':", "# Check each field definition in the set of mappings for map_def in", "- used in string slicing 'db_schema': Name of target schema, 'sheet_name': Name of", "for download directory: %s\" % dirname(file_to_process)) # Handle subsample if process_subsample is not", "charge, to any person obtaining a copy # of this software and associated", ":return: number of rows in the specified schema.table :rtype: int \"\"\" query =", "purposes :rtype: int \"\"\" print(__license__) return 1 #/* ======================================================================= */# #/* Define print_help()", "'table_name': [ { 'db_table': Name of target table, 'db_field': Name of target field,", "the field map classes so we don't have to # have the same", "drop the script name) :type args: list :return: 0 on success and 1", "specified sheet - populate a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "Name of source sheet in input file, 'column': Name of source column in", "straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value =", "======================================================================= */# #/* Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate", "specified file already exists and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress", "process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row']", "1. Get an ID 2. Get a set of field maps for one", "the field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/*", "it is assumed that the specified file already exists and should be used", "row = kwargs['row'] value = row[map_def['column']] if value == 'INC': value = 'INCIDENT'", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, {", "copyright notice and this permission notice shall be included in all copies or", "= kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value =", "# specified in the processing args. Currently not a problem since # Build", "ALL queries. The processing functions are intended to return a final value to", "map with all options: This field map shows that no specific column contains", "purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__),", "have to # have the same existance test for all tables if table=='\"BotTaskStatus\"':", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement - currently", "'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define main() function #/* ======================================================================= */#", "#/* Validate parameters #/* ----------------------------------------------------------------------- */# bail = False # Make sure arguments", "Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in the", "field map but this behavior is not required. If the function itself handles", "map_def['sheet_name']) # Make sure schema and table exist in the DB query =", "# Invalid argument i += 1 arg_error = True print(\"ERROR: Invalid argument: %s\"", "rows as values row The current row being processed - structured just like", "3 } # Database is expecting to handle the normalization by reading from", "Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in the", "----------------------------------------------------------------------- */# i = 0 arg_error = False while i < len(args): try:", "----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD workbook for processing #/* -----------------------------------------------------------------------", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "#/* Python setup #/* ======================================================================= */# if sys.version[0] is 2: range = xrange", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema':", "Define print_version() function #/* ======================================================================= */# def print_version(): \"\"\" Print script version information", "inserts - tell parent process there's nothing left to do return initial_value_to_be_returned #/*", "used in conjunction with --no-download it is assumed that the specified file already", "seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees:", "actually be executed map_def Current map definition being processed (example below) print_queries Specifies", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing':", "report_exists method on each of the field map classes so we don't have", "kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time()", "[default: ''] --download-url URL from which to download the input file --no-download Don't", "{ 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name':", "is a flag that requires parameters but the user did not supply the", "'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype',", "to describe which fields in which sheets should be inserted into which table", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ], } #/*", "else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode,", "were properly parse if arg_error: bail = True print(\"ERROR: Did not successfully parse", "'NrcExtractor' #/* ======================================================================= */# #/* Define main() function #/* ======================================================================= */# def main(args):", "= kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries =", "\"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict()", "- currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid()", "The processing functions are intended to return a final value to be inserted", "\"\"\" :param cursor: Postgres formatted database connection string :type cursor: psycopg2.cursor :param schema_table:", "None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def", "into the table specified in the field map # This query must be", "BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final return #/* -----------------------------------------------------------------------", "row[map_def['processing']['args']['unit_field']] # If the value is not a float, change it to nothing", "additional processing step that is highly specific and cannot be re-used. The field", "db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/*", "in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET' #/* -----------------------------------------------------------------------", "arg == '--print-queries': i += 1 print_queries = True print_progress = False elif", "always receive the following kwargs: all_field_maps All field maps with keys set to", "= \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */#", "map_def = kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if value == 'INC':", "], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "*/# #/* Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return", "for exit code purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help More detailed", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None },", "NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter() protected", "return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */#", "'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } },", "is hereby granted, free of charge, to any person obtaining a copy of", "process_subsample is not None and process_subsample < len(unique_report_ids): # TODO: Delete constraining line", "db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL'", "process # Get a set of field maps for a single table to", "download_file = False elif arg == '--download-url': i += 2 download_url = args[i", "None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC',", "three conditions: # 1. The last argument is a flag that requires parameters", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing':", "*/# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id()", "of target table, 'db_field': Name of target field, 'db_field_width': Maximum width for this", "#/* ======================================================================= */# #/* Define print_license() function #/* ======================================================================= */# def print_license(): \"\"\"", "function #/* ======================================================================= */# def print_version(): \"\"\" Print script version information :return: 1", "\"\"\" Detailed help information :return: 1 for exit code purposes :rtype: int \"\"\"", "e: print(\"ERROR: Could not connect to database: %s\" % db_connection_string) print(\" Postgres Error:", "#/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information", "map_def['db_field'])) # Encountered an error validating the field map if validate_field_map_error: db_cursor.close() db_conn.close()", "None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */# #/*", "the target table, skip everything else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor,", "def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */#", "# TODO: Implement - check notes about which column to use 'db_table': '\"NrcParsedReport\"',", "execution Automatically turns off the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \"", "indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/*", "receive the following kwargs: all_field_maps All field maps with keys set to schema.table", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "*/# #/* Cache initial DB row counts for final stat printing #/* -----------------------------------------------------------------------", "isinstance(value, str) or isinstance(value, unicode): # Having single quotes in the string causes", "======================================================================= */# #/* Define column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\"", "'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public',", "elif arg == '--print-queries': i += 1 print_queries = True print_progress = False", "False elif arg == '--download-url': i += 2 download_url = args[i - 1]", "on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" %", "a csv.DictReader row sheet The entire sheet from which the row was extracted", "if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing function handled ALL", "seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower() not in", "in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more", "a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row", "code purposes :rtype: int \"\"\" print(\"\"\" %s version %s - released %s \"\"\"", "(schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\" %", "#/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs):", "*/# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */#", "in (None, '', u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode): value =", "for a given ID is as follows: 1. Get an ID 2. Get", "merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # #", "the value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be sent", "on success and 1 on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/*", "----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\"", "'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public',", "check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public',", "workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache)", "*/# # Handle NULL values - these should be handled elsewhere so this", "elif arg in ('--help', '-help', '--h', '-h'): return print_help() elif arg in ('--usage',", "minimum field map example below states that whatever value is in sheet 'CALLS'", "'\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, {", "'processing': { 'function': NrcParsedReportFields.areaid } }, { # TODO: Implement - check notes", "Define print_help() function #/* ======================================================================= */# def print_help(): \"\"\" Detailed help information :return:", "0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280,", "The field in all sheets containing the reportnum uid The current SEQNOS/reportnum being", "None: try: value = row[map_def['column']] except KeyError: # UID doesn't appear in the", "None }, Example field map with all options: This field map shows that", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "processed (example below) print_queries Specifies whether or not queries should be printed as", "2 db_connection_string = args[i - 1] elif arg == '--db-host': i += 2", "\"\"\" Main routine to parse, transform, and insert Current.xlsx into the tables used", "schema. Each field map is applied against each ID which means that if", "query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column':", "1 # Prep workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as", "of mappings for map_def in field_map[db_map]: # Attempt to get the sheet to", "(unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done processing - update user", "kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* -----------------------------------------------------------------------", "'\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp,", "containing the reportnum uid The current SEQNOS/reportnum being processed workbook XLRD workbook object", "tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set", "map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor']", "sure the value is properly quoted if value not in (None, '', u'',", "charge, to any person obtaining a copy of this software and associated documentation", "handled by the parent process so this value is # returned at the", "More Row 1 Values' }, { 'Column1': 'Row 2 Val', 'Column2': 'Another Row", ":return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1}", "2014 SkyTruth # # Permission is hereby granted, free of charge, to any", "single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value)", "'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } },", "row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/*", "has not been specified, blindly overwrite the file. Unless the user is specifying", "try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download from URL: %s\"", "persons to whom the Software is furnished to do so, subject to the", "is None or not value: value = db_null_value # Assemble query if value", "--db-pass Password for database user [default: ''] --download-url URL from which to download", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file straight into DB #/*", "print(\"Validating field mapping ...\") for db_map in field_map_order: # Check each field definition", "s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) #", "= {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional", "if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */#", "sublicense, and/or sell # copies of the Software, and to permit persons to", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static method #/* ----------------------------------------------------------------------- */#", "'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id',", "a safety net if value is None or not value: value = db_null_value", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP',", "and row by row, a set of field map definitions are declared to", "== '--no-execute-queries': i += 1 execute_queries = False # Additional options elif arg", "'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public',", "# Help arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif", "hack with something better. # Perhpas have a report_exists method on each of", "Only put quotes around specific values if isinstance(value, str) or isinstance(value, unicode): #", "in the Software without restriction, including without limitation the rights to use, copy,", "to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that a specific function must", "'%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not", "License (MIT) # # Copyright (c) 2014 SkyTruth # # Permission is hereby", "the --file-to-process already exists and --no-download has not been specified, blindly overwrite the", "'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"',", "\"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another", "[--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly", "ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output = int(degrees) + int(minutes) / 60", ":param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of", "dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function", "None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema':", "workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return", "'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public',", "= { 'table_name': [ { 'db_table': Name of target table, 'db_field': Name of", "sys.version[0] is 2: range = xrange #/* ======================================================================= */# #/* Build information #/*", "elif arg == '--no-execute-queries': i += 1 execute_queries = False # Additional options", "field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */#", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { # TODO: Not", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL',", "1 on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps", "THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage() function #/* ======================================================================= */#", "final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* -----------------------------------------------------------------------", "2 db_pass = args[i - 1] # Commandline print-outs elif arg == '--no-print-progress':", "----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail = False # Make", "row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If no additional processing", "# Positional arguments and errors else: # Invalid argument i += 1 arg_error", "merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to", "map directly to a column in the database. These fields require an additional", "row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad", "output formatted name :rtype: str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split", "like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static method #/* -----------------------------------------------------------------------", "in 'CALLS' but can be specified by the user. This set of ID's", "associated documentation files (the \"Software\"), to deal in the Software without restriction, including", "workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) #", "csv.DictReader row sheet The entire sheet from which the row was extracted as", "def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static method", "'processing': None }, { # TODO: Implement - check notes about which column", "#/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail = False #", "db_name = 'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO'", "responsible for additional sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ...", "@staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row = kwargs['row'] map_def =", ":type formatter: type|function :return: list of column names :rtype: list \"\"\" return [formatter(cell.value)", "object responsible for additional sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2':", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,", "arg in ('--version', '-version'): return print_version() elif arg in ('--license', '-usage'): return print_license()", "#/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading:", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected',", "to autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline Execution #/*", "{2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/* Define", "does not exist: %s\" % map_def['sheet_name']) # Make sure schema and table exist", "Illegal value: %s\" % iv) if quadrant.lower() not in ('n', 'e', 's', 'w'):", "final return #/* ----------------------------------------------------------------------- */# # Update user padding = max([len(i) for i", "row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None", "= 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url", "DB connections # db_conn.commit() # connection is now set to autocommit db_cursor.close() db_conn.close()", "'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"',", "better organization and to prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\"", "'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public',", "Row 1 Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even", "target table, 'db_field': Name of target field, 'db_field_width': Maximum width for this field", "'\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema':", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema':", "file is not going to be accidentally deleted if download_file and not overwrite_downloaded_file", "recieved_datetime(**kwargs): \"\"\" See documentation for function called in the return statement \"\"\" return", "NrcScrapedMaterialFields.st_id } } ] } } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url',", "method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL", "db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating the field map if", "1 execute_queries = False # Additional options elif arg == '--overwrite-download': i +=", "function takes care of that but must still supply the expected post-normalization format", "- check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema':", "the insert statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public',", "print_progress = True print_queries = False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"',", "quoted if value not in (None, '', u'', db_null_value): if isinstance(value, str) or", "= kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid =", "args[i - 1] # Positional arguments and errors else: # Invalid argument i", "= kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value is", "method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates from DMS to", "# Don't need to process the reportnum information since it was added to", ":rtype: str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0]", "output #/* ======================================================================= */# #/* Define column_names() function #/* ======================================================================= */# def column_names(sheet,", "of 'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3 } #", "Assumed mistyping of 'IN' 'YARDS': 3 } # Database is expecting to handle", "return db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/*", "for public.\"NrcParsedReport\".longitude Instead, some information must be passed to the NrcParsedReportFields.longitude() function where", "bare minimum field map example below states that whatever value is in sheet", "If the value is not a float, change it to nothing so the", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'incidenttype', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'TYPE_OF_INCIDENT', 'processing': None },", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url }", "= kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode =", "iv) if quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant:", "= kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field =", "db_write_mode The first part of the SQL statement for writes (e.g. INSERT INTO)", "overwrite_downloaded_file = True elif arg == '--subsample': i += 2 process_subsample = args[i", "[--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a Postgres", ":type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable", "\"\"\" Database is expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value =", "is as follows: 1. Get an ID 2. Get a set of field", "processed - structured just like a csv.DictReader row sheet The entire sheet from", "schema_table): \"\"\" :param cursor: Postgres formatted database connection string :type cursor: psycopg2.cursor :param", "'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public',", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return", "{ 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field':", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None", "return a final value to be inserted into the target field described in", "map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] #", "Don't download the input file --overwrite-download If the --file-to-process already exists and --no-download", "Error: %s\" % e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet", "something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/*", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None", "check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public',", "== '--db-host': i += 2 db_host = args[i - 1] elif arg ==", "inserted into the target field described in the field map but this behavior", "workbook = kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet", "value is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\"", "db_seqnos_field=db_seqnos_field) # Make sure the value is properly quoted if value not in", "def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries =", "'IN' 'YARDS': 3 } # Database is expecting to handle the normalization by", "# TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing':", "----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement - currently returning NULL return", "= 0 # Loop through the primary keys for uid in unique_report_ids: #", "do not map directly to a column in the database. These fields require", "Name of target table, 'db_field': Name of target field, 'db_schema': Name of target", "2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\" Example", "in sheet_dict} except IndexError: # Sheet was empty pass # Get a list", "of being inserted into Postgres timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp,", "} } }, ], 'TABLE_NAME': [ { 'db_table': Name of target table, 'db_field':", "#/* ======================================================================= */# #/* Define print_help() function #/* ======================================================================= */# def print_help(): \"\"\"", "is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT", "(%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query)", "and to prevent having to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* -----------------------------------------------------------------------", "time workbook = kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode)", "\"\"\" Command line usage information :return: 1 for exit code purposes :rtype: int", "Exception as e: print (\"Error printing SQL query to console (unicode weirdness?\") print", "parameters for an argument # 3. The arg parser did not properly iterate", "sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample", "import division from __future__ import print_function from __future__ import unicode_literals from datetime import", "do more of the heavy lifting. Field maps are grouped by table and", "# UID doesn't appear in the specified sheet - populate a NULL value", "downloaded file :type destination: str|unicode :param overwrite: specify whether or not an existing", "number to process # Get a set of field maps for a single", "= sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If no additional processing is", ":return: path to downloaded file :rtype: str|unicode \"\"\" # Validate arguments if not", "Could not get the sheet to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR:", ":return: decimal degrees :rtype: float \"\"\" illegal_vals = (None, '', u'') for iv", "whether or not queries should be printed as they are executed raw_sheet_cache Structured", "for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' *", "deal in the Software without restriction, including without limitation the rights to use,", "(file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the sheet to test except xlrd.XLRDError:", "sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return: list of column names :rtype:", "Postgres timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/*", "'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public',", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "return 1 #/* ======================================================================= */# #/* Define print_license() function #/* ======================================================================= */# def", "'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "properly quoted if value not in (None, '', u'', db_null_value): if isinstance(value, str)", "} } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS',", "KeyError: # UID doesn't appear in the specified sheet - populate a NULL", "The cursor to be used for all queries db_null_value Value to use for", "= 'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() +", "*/# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error = False", "elif arg in ('--version', '-version'): return print_version() elif arg in ('--license', '-usage'): return", "} # Database is expecting to handle the normalization by reading from a", "% quadrant) output = int(degrees) + int(minutes) / 60 + int(seconds) / 3600", "kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode']", "== '--no-print-progress': i += 1 print_progress = False elif arg == '--print-queries': i", "'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } },", "map to process for map_def in field_map[db_map]: # Don't need to process the", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None },", "[--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite]", "'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } },", "Print queries immediately before execution Automatically turns off the progress indicator --no-execute-queries Don't", "return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/* ======================================================================= */# def", "from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None:", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "return value #/* ======================================================================= */# #/* Define NrcParsedReportFields() class #/* ======================================================================= */# class", "row = None # If no additional processing is required, simply grab the", "@staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value',", "'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } } ],", "\"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\" \"Row 2", "(padding - len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor,", "for uid in unique_report_ids: # Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\"", "to process # Get a set of field maps for a single table", "has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */# #", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */#", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { # TODO: Not populated 'db_table':", "{ 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None", "not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant)", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */#", "= ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */#", "A class is used as a namespace to provide better organization and to", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "division from __future__ import print_function from __future__ import unicode_literals from datetime import datetime", "KeyError): output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define latitude() static", "calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value", "formatter: type|function :return: list of column names :rtype: list \"\"\" return [formatter(cell.value) for", "None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] } } } }, {", "* (padding - len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts = {ts:", "try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row", "arg == '--db-pass': i += 2 db_pass = args[i - 1] # Commandline", ":type minutes: int :param seconds: coordinate seconds :type seconds: int :param quadrant: coordinate", "1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB row counts for final stat", "map_def in field_map[db_map]: # Attempt to get the sheet to test if map_def['sheet_name']", "#/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called function documentation \"\"\" return", "\\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results:", "(overwrite, destination)) # Download response = urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read())", "field map to process for map_def in field_map[db_map]: # Don't need to process", "__version__, __release__)) return 1 #/* ======================================================================= */# #/* Define dms2dd() function #/* =======================================================================", "table, field, reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define timestamp2datetime()", "if a report has already been submitted to a table :param seqnos: reportnum", "sell # copies of the Software, and to permit persons to whom the", "None and map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not", "line usage information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\"", "print(query) if execute_queries: db_cursor.execute(query) # This processing function handled ALL inserts - tell", "= args[i - 1] elif arg == '--db-user': i += 2 db_user =", "db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could not", "\" \" * len(__docname__))) return 1 #/* ======================================================================= */# #/* Define print_license() function", "--db-user `whoami` --db-host localhost \"\"\" from __future__ import division from __future__ import print_function", "% value) # String value else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field'])", "== '--db-pass': i += 2 db_pass = args[i - 1] # Commandline print-outs", "#/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\"", "'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': {", "keys for uid in unique_report_ids: # Update user uid_i += 1 if print_progress:", "*/# #/* Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant):", "SQL query to console (unicode weirdness?\") print (e.message) if execute_queries: db_cursor.execute(query) # Done", "%s version %s - released %s \"\"\" % (__docname__, __version__, __release__)) return 1", "len(schema_table) + 4), count)) print(\"New rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" %", "subsample min - must be an int: %s\" % process_subsample) # Exit if", "def ft_id(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None)", "'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field)", "'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"',", "the Software is furnished to do so, subject to the following conditions: The", "Row 1 Val', 'Column3': 'Even More Row 1 Values' }, { 'Column1': 'Row", ":rtype: int \"\"\" print(__license__) return 1 #/* ======================================================================= */# #/* Define print_help() function", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county',", "= \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \",", "error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/* -----------------------------------------------------------------------", "arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error = False while i <", "See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width()", "name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "sheet_seqnos_field The field in all sheets containing the reportnum uid The current SEQNOS/reportnum", "*/# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return", "st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/* =======================================================================", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id',", "'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "not None and process_subsample < len(unique_report_ids): # TODO: Delete constraining line - needed", "return 'NrcExtractor' #/* ======================================================================= */# #/* Define main() function #/* ======================================================================= */# def", "Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define", "map and NOT the extra field maps # specified in the processing args.", "as values row The current row being processed - structured just like a", "iterate the 'i' variable except IndexError: i += 1 arg_error = True print(\"ERROR:", "*/# #/* Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\"", "_sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value", "sheets should be inserted into which table in which schema. Each field map", "reads rows from the sheet specified in the field map and NOT the", "'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "License (MIT) Copyright (c) 2014 SkyTruth Permission is hereby granted, free of charge,", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' #/* =======================================================================", "if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write permission for download", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "schema.table db_cursor The cursor to be used for all queries db_null_value Value to", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "in the specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\"", "Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string = None db_host = 'localhost' db_name", "value required for public.\"NrcParsedReport\".longitude Instead, some information must be passed to the NrcParsedReportFields.longitude()", "user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters", "os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write permission for download directory: %s\"", "workbook ...\") num_ids = len(unique_report_ids) uid_i = 0 # Loop through the primary", "'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without", "fields require an additional processing step that is highly specific and cannot be", "arg == '--file-to-process': i += 2 file_to_process = abspath(args[i - 1]) # Database", "specific and cannot be re-used. The field map definition contains all of the", "assumed that the specified file already exists and should be used for processing", "\"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall()", "sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries", "[ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing':", "def main(args): \"\"\" Main routine to parse, transform, and insert Current.xlsx into the", "sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value", "left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method", "print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i = 0 # Loop through the", "'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "*/# def main(args): \"\"\" Main routine to parse, transform, and insert Current.xlsx into", "Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another Row 3", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "by sheet and row by row, a set of field map definitions are", "======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date", "if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" %", "'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"',", "of the SQL statement for writes (e.g. INSERT INTO) execute_queries Specifies whether or", "@staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class", "time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert", "getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value =", "'Arg1': parameter, 'Arg2': ... } } } ], } The order of operations", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "in field_map.keys()]) indent = \" \" * 2 print(\"Initial row counts:\") for schema_table,", "= sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict}", "value = db_null_value # Pass all necessary information to the processing function in", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is properly quoted if value", "args[i - 1] elif arg == '--file-to-process': i += 2 file_to_process = abspath(args[i", "person obtaining a copy of this software and associated documentation files (the \"Software\"),", "'\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude,", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': {", "Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement", "Convert a float formatted date a Postgres supported timestamp :param stamp: timestamp from", "'--overwrite-download': i += 1 overwrite_downloaded_file = True elif arg == '--subsample': i +=", "prep #/* ----------------------------------------------------------------------- */# # Cache all sheets needed by the field definitions", "sheet specified in the field map and NOT the extra field maps #", "# Attempt to get the sheet to test if map_def['sheet_name'] is not None", "the field map and NOT the extra field maps # specified in the", "net if value is None or not value: value = db_null_value # Assemble", "--print-queries Print queries immediately before execution Automatically turns off the progress indicator --no-execute-queries", "file_to_process = abspath(args[i - 1]) # Database connection elif arg == '--db-connection-string': i", "= db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\"", "released %s \"\"\" % (__docname__, __version__, __release__)) return 1 #/* ======================================================================= */# #/*", "report has already been submitted to a table :param seqnos: reportnum :type seqnos:", "'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "#/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs):", "----------------------------------------------------------------------- */# #/* Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs):", "[ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing':", "'\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id", "not properly consume all parameters for an argument # 3. The arg parser", "require converting a timestamp to a Postgres supported timestamp format. This method eliminates", "documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static method #/*", "'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] } } } },", "#/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row =", "license information :return: 1 for exit code purposes :rtype: int \"\"\" print(__license__) return", "database: %s\" % db_connection_string) print(\" Postgres Error: %s\" % e) return 1 #/*", "Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement", "1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file:", "information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" %s version", "3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280,", "return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */#", "blindly overwrite the file. Unless the user is specifying a specific target for", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function':", "value else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with", "transformations, a set of SEQNOS/reportnum's are gathered from one of the workbook's sheets.", "to the following conditions: # # The above copyright notice and this permission", "NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "be printed as they are executed raw_sheet_cache Structured similar to the normal sheet", "#/* Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in", "a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id()", "flags, options, etc. --version Version and ownership information --license License information \"\"\") return", "print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/*", "for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries Print queries", "_datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting", "input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function", "1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280,", "string. All other --db-* options are ignored. --db-host Hostname for the target database", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': {", "function handled ALL inserts - tell parent process there's nothing left to do", "value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the query query =", "*/# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */#", "is not a float, change it to nothing so the next test fails", "that a specific function must do more of the heavy lifting. Field maps", "Sheet does not exist: %s\" % map_def['sheet_name']) # Make sure schema and table", "[--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass", "the extra field maps # specified in the processing args. Currently not a", "parameter # 2. The arg parser did not properly consume all parameters for", "str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define", "bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD workbook", "a set of field maps for a single table to process # Get", "Assemble query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes", "to any person obtaining a copy of this software and associated documentation files", "from XLRD reading a date encoded field :type stamp: float :param workbook_datemode: from", "\"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot, }", "except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\" % value)", "'db_field_width': Maximum width for this field - used in string slicing 'db_schema': Name", "NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function", "that is highly specific and cannot be re-used. The field map definition contains", "the input document sheet by sheet and row by row, a set of", "'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public',", "additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to the processing", "db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" %", "psycopg2.OperationalError as e: print(\"ERROR: Could not connect to database: %s\" % db_connection_string) print(\"", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity',", "method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods", "'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name':", "#/* Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value',", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "processing step that is highly specific and cannot be re-used. The field map", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema':", "map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial", "'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None },", "else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the", "rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp()", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, {", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing':", "#/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do", "destination should be overwritten :type overwrite: bool :return: path to downloaded file :rtype:", "1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help More", "def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require the same general logic.", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB connection and turn", "See called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area()", "'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { # TODO: Implement - check", "return print_help() elif arg in ('--usage', '-usage'): return print_usage() elif arg in ('--version',", "if sys.version[0] is 2: range = xrange #/* ======================================================================= */# #/* Build information", "supply the parameter # 2. The arg parser did not properly consume all", "and information necessary to execute one of these processing functions. A class is", "utility --usage Arguments, parameters, flags, options, etc. --version Version and ownership information --license", "destination)) # Download response = urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None },", "if bail: return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD", "to the second. --file-to-process Specify where the input file will be downloaded to", "which fields in which sheets should be inserted into which table in which", "*/# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail = False # Make sure", "#/* Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value',", "None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "errors else: # Invalid argument i += 1 arg_error = True print(\"ERROR: Invalid", "user padding = max([len(i) for i in field_map.keys()]) indent = \" \" *", "import xlrd #/* ======================================================================= */# #/* Python setup #/* ======================================================================= */# if sys.version[0]", "copy of this software and associated documentation files (the \"Software\"), to deal in", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ],", ":type sheet: xlrd.Sheet :return: list of elements, each containing one row of the", "E, S, W) :type quadrant: str|unicode :return: decimal degrees :rtype: float \"\"\" illegal_vals", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not populated", "notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name':", "1 Val', 'Column3': 'Even More Row 1 Values' }, { 'Column1': 'Row 2", "quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/*", "without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,", "elements, each containing one row of the sheet as a dictionary :rtype: dict", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company", "in all # copies or substantial portions of the Software. # # THE", "'\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype", "'.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing function handled", "should be inserted into which table in which schema. Each field map is", "result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field,", "map below shows that the value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS'", "else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "{ 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name':", "still supply the expected post-normalization format if unit.upper() not in multipliers: return db_null_value", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "return 1 #/* ======================================================================= */# #/* Define print_help() function #/* ======================================================================= */# def", "1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2}", "value == '' or unit == '': return db_null_value # Found a sheen", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None", "TODO: replace this hack with something better. # Perhpas have a report_exists method", "Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method", "{ 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public', 'extras_field_maps': { 'public.\"NrcScrapedReport\"': [", "*/# #/* Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\"", "#/* ----------------------------------------------------------------------- */# #/* Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but", "input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "drive processing. Rather than process the input document sheet by sheet and row", "which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific values if", "return [formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function", "{ 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name':", "a table. The structure for field maps is roughly as follows: All field", "the report already exists, in the target table, skip everything else _schema, _table", "gathered from one of the workbook's sheets. The default column in 'CALLS' but", "goes into the table specified in the field map # This query must", "not if the report already exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\"", "be specified by the user. This set of ID's are treated as primary", "*/# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields", "modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and", "True process_subsample = None process_subsample_min = 0 # User feedback settings print_progress =", "(uid_i, num_ids)) sys.stdout.flush() # Get field maps for one table for db_map in", "publish, distribute, sublicense, and/or sell # copies of the Software, and to permit", "\"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/*", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "1 #/* ======================================================================= */# #/* Define print_help() function #/* ======================================================================= */# def print_help():", "'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public',", "information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" Help: {0}", "bare minimum field map: The field map below shows that the value in", "print_progress = False elif arg == '--print-queries': i += 1 print_queries = True", "from os.path import * import sys import urllib2 import psycopg2 import psycopg2.extras import", "rows, each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row", "TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE',", "Row 3 Val\",\"Even More Row 3 Values\" Example Output: [ { 'Column1': 'Row", "insert Current.xlsx into the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing", "processing args. Currently not a problem since # Build query initial_value_to_be_returned = None", "----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries =", "kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if value == 'INC': value =", "i += 1 overwrite_downloaded_file = True elif arg == '--subsample': i += 2", "execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field", "'--download-url': i += 2 download_url = args[i - 1] elif arg == '--file-to-process':", "table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace", "str|unicode :return: output formatted name :rtype: str|unicode \"\"\" dt = datetime.now() dt =", "= {} raw_sheet_cache = {} for sname in workbook.sheet_names(): if sname not in", "for ALL queries. The processing functions are intended to return a final value", "input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try:", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "decimal degrees :param degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes", "# Cache all sheets needed by the field definitions as dictionaries print(\"Caching sheets", "to the NrcParsedReportFields.longitude() function where the actual processing happens. Field maps using additional", "added to the initial query above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field]", "FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table, reportnum)) else:", "argument i += 1 arg_error = True print(\"ERROR: Invalid argument: %s\" % arg)", "the Software, and to permit persons to whom the Software is furnished to", "list of unique report id's unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems():", "\"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static method #/* -----------------------------------------------------------------------", "parameters, flags, options, etc. --version Version and ownership information --license License information \"\"\")", "'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that", "return output #/* ======================================================================= */# #/* Define column_names() function #/* ======================================================================= */# def", "means that if ID number 1234 is being processed, the bare minimum field", "been specified, blindly overwrite the file. Unless the user is specifying a specific", "'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public',", "'\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, {", "'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name':", "'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } }, { # TODO: Implement -", "process_subsample_min = 0 # User feedback settings print_progress = True print_queries = False", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema':", "name (e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted name :rtype: str|unicode \"\"\"", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing': None", "Detailed help information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\"", "capable of being inserted into Postgres timestamp field :rtype: str|unicode \"\"\" dt =", "} }, ], 'TABLE_NAME': [ { 'db_table': Name of target table, 'db_field': Name", "so we don't have to # have the same existance test for all", "user is specifying a specific target for the download, this flag is not", "file :rtype: str|unicode \"\"\" # Validate arguments if not overwrite and isfile(destination): raise", "result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field,", "# Exit if any problems were encountered if bail: return 1 #/* -----------------------------------------------------------------------", "--download-url URL from which to download the input file --no-download Don't download the", "60 + int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output *= -1", "schema.table :type schema_table: str|unicode :return: number of rows in the specified schema.table :rtype:", "#/* Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse", "localhost] --db-user Username used for database connection [default: current user] --db-name Name of", "e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */#", "to name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status()", "======================================================================= */# #/* Define print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\" Print", "source sheet in input file, 'column': Name of source column in sheet_name, 'processing':", "#/* ----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs):", "structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even", "this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If", "declared to describe which fields in which sheets should be inserted into which", "- 1] # Positional arguments and errors else: # Invalid argument i +=", "is furnished to do so, subject to the following conditions: The above copyright", "any transformations, a set of SEQNOS/reportnum's are gathered from one of the workbook's", "print(\"ERROR: Invalid subsample or subsample min - must be an int: %s\" %", "not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET' #/*", "task_id = %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE", "'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process =", "len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define timestamp2datetime() function #/* ======================================================================= */#", "platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement -", "target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating", "None, 'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema':", "maps are grouped by table and center around the target field. There should", "supported connection string. All other --db-* options are ignored. --db-host Hostname for the", "using additional processing always receive the following kwargs: all_field_maps All field maps with", "'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } },", "of target field, 'db_field_width': Maximum width for this field - used in string", "INSERT INTO) execute_queries Specifies whether or not queries should actually be executed map_def", "spreadsheet do not map directly to a column in the database. These fields", "seqnos: reportnum :type seqnos: int|float :param field: :type field: :return: :rtype: bool \"\"\"", "#/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods", "target for the download, this flag is not needed due the default file", "print_progress = False elif arg == '--no-execute-queries': i += 1 execute_queries = False", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "field, 'db_field_width': Maximum width for this field - used in string slicing 'db_schema':", "to permit persons to whom the Software is furnished to do so, subject", "perform conversion else: multipliers = { 'F': 1, 'FE': 1, 'FEET': 1, 'IN':", "is expecting to handle the normalization by reading from a field containing \"1.23", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None", "*/# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database connection string :type", "#/* ----------------------------------------------------------------------- */# # Update user padding = max([len(i) for i in field_map.keys()])", "'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table':", "sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the", "processing functions are intended to return a final value to be inserted into", "field definition in the set of mappings for map_def in field_map[db_map]: # Attempt", "each of the field map classes so we don't have to # have", "NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define blockid() static method #/*", "and assemble an insert query 4. Execute the insert statement 5. Repeat steps", "= kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def =", "entire sheet from which the row was extracted as described in the field", "quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv) if quadrant.lower() not in ('n',", "row, a set of field map definitions are declared to describe which fields", "which schema. Each field map is applied against each ID which means that", "Implement - check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid',", "substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "*/# #/* Adjust options #/* ----------------------------------------------------------------------- */# # Database - must be done", "col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output", "= True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map definitions", "row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* ----------------------------------------------------------------------- */# #/*", "in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv) if", "field_map[db_map]: # Attempt to get the sheet to test if map_def['sheet_name'] is not", "else: # Get the row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except", "restriction, including without limitation the rights # to use, copy, modify, merge, publish,", "'' or unit == '': return db_null_value # Found a sheen size and", "{ # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } } ], }", "of unique report id's unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems(): for", "Default value \"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method", "Error: %s\" % e) return 1 # Prep workbook print(\"Opening workbook: %s\" %", "connection [default: current user] --db-name Name of target database [default: skytruth] --db-pass Password", "rows from the sheet specified in the field map and NOT the extra", "whether or not queries should actually be executed map_def Current map definition being", "Don't print the progress indicator --print-queries Print queries immediately before execution Automatically turns", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* -----------------------------------------------------------------------", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees':", "for a single table to process # Get a field map to process", "sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Add this", "str|unicode :param overwrite: specify whether or not an existing destination should be overwritten", "import datetime import getpass import os from os.path import * import sys import", "by row, a set of field map definitions are declared to describe which", "'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table':", "value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "field: :type field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor']", "db_cursor.execute(query) # This processing function handled ALL inserts - tell parent process there's", "the user is specifying a specific target for the download, this flag is", "timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date a Postgres supported", "the target field described in the field map but this behavior is not", "----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement - currently returning NULL return", "MIT License (MIT) # # Copyright (c) 2014 SkyTruth # # Permission is", "conditions: # 1. The last argument is a flag that requires parameters but", "'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, }", "and associated documentation files (the \"Software\"), to deal in the Software without restriction,", "----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp to", "quadrant) output = int(degrees) + int(minutes) / 60 + int(seconds) / 3600 if", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "for additional sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... }", "% db_connection_string) print(\" Postgres Error: %s\" % e) return 1 #/* ----------------------------------------------------------------------- */#", "the specified file already exists and should be used for processing [default: Current_<CURRENT_DATETIME>.xlsx]", "int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output", "method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement - currently returning", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field']", "None }, { # TODO: Implement - check notes about which column to", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "= False print(\"Validating field mapping ...\") for db_map in field_map_order: # Check each", "kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] if map_def['processing'] is", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "* (padding - len(schema_table) + 4), count)) print(\"New rows:\") for schema_table, count in", "if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */# #/* Cache initial DB", "be done here in order to allow the user to overwrite the default", "object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements, each containing one", "and filename for downloaded file :type destination: str|unicode :param overwrite: specify whether or", "(indent, schema_table + ' ' * (padding - len(schema_table) + 4), count)) print(\"Final", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "DB connection and turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True", "{ 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name':", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { # TODO: Implement - check", "# String value else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do", "NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object):", "all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is", "statement for writes (e.g. INSERT INTO) execute_queries Specifies whether or not queries should", "'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER':", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.areaid } }, { # TODO: Implement", "FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s' AND column_name =", "from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of being inserted into Postgres", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"',", "Exit if any problems were encountered if bail: return 1 #/* ----------------------------------------------------------------------- */#", "* FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table, reportnum))", "commandline (sys.argv[1:] in order to drop the script name) :type args: list :return:", "that if ID number 1234 is being processed, the bare minimum field map", "= kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field =", "--no-download has not been specified, blindly overwrite the file. Unless the user is", "e: print (\"Error printing SQL query to console (unicode weirdness?\") print (e.message) if", "'Column1': 'Row 3 Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even more Row", "'': return db_null_value # Found a sheen size and unit - perform conversion", "= False elif arg == '--print-queries': i += 1 print_queries = True print_progress", "the target database [default: localhost] --db-user Username used for database connection [default: current", "XLRD sheet object into a list of rows, each structured as a dictionary", "submitted to a table :param seqnos: reportnum :type seqnos: int|float :param field: :type", "'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table':", "'column': None, 'processing': { 'function': BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */#", "'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { #", "definition being processed (example below) print_queries Specifies whether or not queries should be", "an ID 2. Get a set of field maps for one target table", "in map_def['processing']['function'] is responsible for ALL queries. The processing functions are intended to", "2: range = xrange #/* ======================================================================= */# #/* Build information #/* ======================================================================= */#", "internally it can return '__NO_QUERY__' in order to be excluded from the insert", "processing. Note the quotes around the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company',", "*/# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet object into a list of", "if quadrant.lower() in ('s', 'w'): output *= -1 return output #/* ======================================================================= */#", "'\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, {", "None # If no additional processing is required, simply grab the value from", "'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "for database user [default: ''] --download-url URL from which to download the input", "is applied against each ID which means that if ID number 1234 is", "conditions: # # The above copyright notice and this permission notice shall be", "from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements, each containing one row", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "documentation files (the \"Software\"), to deal # in the Software without restriction, including", "results: validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'],", "#/* ======================================================================= */# def print_help(): \"\"\" Detailed help information :return: 1 for exit", "'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { # TODO: Implement - check notes", "return 1 #/* ----------------------------------------------------------------------- */# #/* Prep DB connection and XLRD workbook for", "_datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp to a Postgres supported timestamp", "{ 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD'", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "Specify where the input file will be downloaded to If used in conjunction", "these processing functions. A class is used as a namespace to provide better", "and rows as values row The current row being processed - structured just", "options: This field map shows that no specific column contains the value required", "--version Version and ownership information --license License information \"\"\") return 1 #/* =======================================================================", "raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] # Found a matching row if", "'' # No sheen size - nothing to do if value == ''", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a", "URL: %s\" % download_url) print(\" URLLIB Error: %s\" % e) return 1 #", "parameter, 'Arg2': ... } } } ], } The order of operations for", "'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note", "the specified sheet - populate a NULL value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "print_function from __future__ import unicode_literals from datetime import datetime import getpass import os", "print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for", "functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static method", "set to autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline Execution", "Delete constraining line - needed to verify everything was wroking unique_report_ids = [i", "archival :param input_name: input file name (e.g. Current.xlsx) :type input_name: str|unicode :return: output", "method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required to insert a NULL", "'column': 'LOCATION_ZIP', 'processing': None }, { # TODO: Implement - check notes about", "inserted into Postgres timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return", "process_subsample_min = args[i - 1] # Positional arguments and errors else: # Invalid", "{ 'Column1': 'Row 1 Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even More", "be excluded from the insert statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field':", "Software is furnished to do so, subject to the following conditions: The above", "# Get a field map to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids)", "= urllib2.urlopen(url) with open(destination, 'w') as f: f.write(response.read()) return destination #/* ======================================================================= */#", "header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output #/* ======================================================================= */#", "'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "print (e.message) if execute_queries: db_cursor.execute(query) # Done processing - update user if print_progress:", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "row[sheet_seqnos_field] == uid: # The first instance goes into the table specified in", "field maps # specified in the processing args. Currently not a problem since", "python # This document is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== #", "argument: %s\" % arg) # This catches three conditions: # 1. The last", "# SOFTWARE. # # =================================================================================== # \"\"\" Scraper for the \"temporary\" NRC incident", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name':", "the actual processing happens. Field maps using additional processing always receive the following", "of rows, each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another", "reportnum uid The current SEQNOS/reportnum being processed workbook XLRD workbook object The callable", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "}, ], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/* ----------------------------------------------------------------------- */# #", "None, 'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema':", "None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "+ name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample = None process_subsample_min =", "files (the \"Software\"), to deal in the Software without restriction, including without limitation", "#/* ======================================================================= */# if sys.version[0] is 2: range = xrange #/* ======================================================================= */#", "Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called", "sheet to test if map_def['sheet_name'] is not None and map_def['column'] is not None:", "#/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process)", "for writes (e.g. INSERT INTO) execute_queries Specifies whether or not queries should actually", "'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url }", "*/# # Update user padding = max([len(i) for i in field_map.keys()]) indent =", "+= 1 arg_error = True print(\"ERROR: An argument has invalid parameters\") #/* -----------------------------------------------------------------------", "False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/*", "permission for download directory: %s\" % dirname(file_to_process)) # Handle subsample if process_subsample is", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status',", "*/# #/* Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): #", "\"\"\" # TODO: Use 24 hour time workbook = kwargs['workbook'] row = kwargs['row']", "elif arg in ('--usage', '-usage'): return print_usage() elif arg in ('--version', '-version'): return", "Invalid argument: %s\" % arg) # This catches three conditions: # 1. The", "*/# @staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static", "value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/*", "map shows that no specific column contains the value required for public.\"NrcParsedReport\".longitude Instead,", ":param cursor: Postgres formatted database connection string :type cursor: psycopg2.cursor :param schema_table: schema.table", "= int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid subsample", "table_schema = '%s' AND table_name = '%s' AND column_name = '%s';\" \\ %", "= value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\"", "Username used for database connection [default: current user] --db-name Name of target database", "write permission to the target directory if not os.access(dirname(file_to_process), os.W_OK): bail = True", "from datetime import datetime import getpass import os from os.path import * import", "[default: skytruth] --db-pass Password for database user [default: ''] --download-url URL from which", "maps # specified in the processing args. Currently not a problem since #", "======================================================================= */# #/* Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor =", "argument is a flag that requires parameters but the user did not supply", "class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet", "query #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if the report already", "#/* ======================================================================= */# #/* Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor", "*/# #/* Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return", "destination, overwrite=False): \"\"\" Download a file :param url: URL to download from :type", "0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3 } # Database is expecting", "True print(\"ERROR: Invalid subsample or subsample min - must be an int: %s\"", "'\"') # Single quotes cause problems on insert try: if e_map_def['db_field_width']: value =", "Loop through the primary keys for uid in unique_report_ids: # Update user uid_i", "kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value']", "#/* ======================================================================= */# def print_version(): \"\"\" Print script version information :return: 1 for", "for iv in illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR:", "localhost \"\"\" from __future__ import division from __future__ import print_function from __future__ import", "overwrite: bool :return: path to downloaded file :rtype: str|unicode \"\"\" # Validate arguments", "input file --no-download Don't download the input file --overwrite-download If the --file-to-process already", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.ft_id } }, { 'db_table':", "... } } } ], } The order of operations for a given", "- should be set to None if not used 'function': Callable object responsible", "value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/*", "spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "def longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/*", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", ":type workbook: :param row: :type row: :param map_def: :type map_def: :rtype: :return: \"\"\"", "\"\"\" Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees", "name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static", "1 arg_error = True print(\"ERROR: Invalid argument: %s\" % arg) # This catches", "None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema':", "'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments from the commandline (sys.argv[1:]", "the set of mappings for map_def in field_map[db_map]: # Attempt to get the", "and download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the user", "print_queries: print(\"\") try: print(query) except Exception as e: print (\"Error printing SQL query", "str|unicode \"\"\" # Validate arguments if not overwrite and isfile(destination): raise ValueError(\"ERROR: Overwrite=%s", "field map and NOT the extra field maps # specified in the processing", "' * (padding - len(schema_table) + 4), count)) print(\"New rows:\") for schema_table, count", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.blockid } }, { 'db_table': '\"NrcParsedReport\"',", "db_null_value # Assemble query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only", "a list of help related flags :return: 1 for exit code purposes :rtype:", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "('--help', '-help', '--h', '-h'): return print_help() elif arg in ('--usage', '-usage'): return print_usage()", "None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC',", "connection string :type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return: number", "OR OTHER DEALINGS IN THE # SOFTWARE. # # =================================================================================== # \"\"\" Scraper", "True print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name']) # Make sure schema", "process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid']", "4), count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "exists and --no-download has not been specified, blindly overwrite the file. Unless the", "min - must be an int: %s\" % process_subsample) # Exit if any", "ID 2. Get a set of field maps for one target table 3.", "from __future__ import unicode_literals from datetime import datetime import getpass import os from", "is # returned at the very end if initial_value_to_be_returned is None: initial_value_to_be_returned =", "sheet object :type sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return: list of", "'function': BotTaskStatusFields.bot, } }, ], } #/* ----------------------------------------------------------------------- */# #/* Define Defaults #/*", "======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not", "row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps", "the field map arguments for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value", "Having single quotes in the string causes problems on insert because the entire", "to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def,", "value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value else: extra_query_values.append(\"%s\" %", "[i for i in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min", "Before doing any transformations, a set of SEQNOS/reportnum's are gathered from one of", "information \"\"\") return 1 #/* ======================================================================= */# #/* Define print_version() function #/* =======================================================================", "More detailed description of this utility --usage Arguments, parameters, flags, options, etc. --version", "'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param args: arguments from", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table':", "1] elif arg == '--subsample-min': i += 2 process_subsample_min = args[i - 1]", "reportnum information since it was added to the initial query above if map_def['db_field']", "Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, ], 'TABLE_NAME': [ {", "public.\"NrcParsedReport\".longitude Instead, some information must be passed to the NrcParsedReportFields.longitude() function where the", "a set of field map definitions are declared to describe which fields in", "populate a NULL value value = db_null_value # Pass all necessary information to", "degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes :type minutes: int", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE',", "database [default: skytruth] --db-pass Password for database user [default: ''] --download-url URL from", "Instead, some information must be passed to the NrcParsedReportFields.longitude() function where the actual", "(indent, schema_table + ' ' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table] -", "are ignored. --db-host Hostname for the target database [default: localhost] --db-user Username used", "'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "*/# #/* Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\"", "permission notice shall be included in all copies or substantial portions of the", "and cannot be re-used. The field map definition contains all of the additional", "in the processing args. Currently not a problem since # Build query initial_value_to_be_returned", "*/# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to", "table and center around the target field. There should be one map for", "'\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name,", "and errors else: # Invalid argument i += 1 arg_error = True print(\"ERROR:", "3 Values' } ] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet:", "seconds: coordinate seconds :type seconds: int :param quadrant: coordinate quadrant (N, E, S,", "kwargs['row'] value = row[map_def['column']] if value == 'INC': value = 'INCIDENT' return value", "= db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "in the DB query = \"SELECT * FROM information_schema.columns WHERE table_schema = '%s'", "unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/*", "'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "NOT the extra field maps # specified in the processing args. Currently not", "return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method #/* ----------------------------------------------------------------------- */#", "in the Software without restriction, including without limitation the rights # to use,", "'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None }, { 'db_table':", "'Column3': 'Even more Row 3 Values' } ] :param sheet: XLRD sheet object", "skytruth] --db-pass Password for database user [default: ''] --download-url URL from which to", "arg in ('--usage', '-usage'): return print_usage() elif arg in ('--version', '-version'): return print_version()", "from :type url: str|unicode :param destination: target path and filename for downloaded file", "True print_queries = False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/*", "subsample or subsample min - must be an int: %s\" % process_subsample) #", "*/# #/* Define print_usage() function #/* ======================================================================= */# def print_usage(): \"\"\" Command line", "raise ValueError(\"ERROR: Overwrite=%s and outfile exists: %s\" % (overwrite, destination)) # Download response", "are executed raw_sheet_cache Structured similar to the normal sheet cache, but with a", "#/* ----------------------------------------------------------------------- */# # Cache all sheets needed by the field definitions as", "db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value", "elif arg == '--db-host': i += 2 db_host = args[i - 1] elif", "kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If the value is not", "def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define", "the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of SEQNOS/reportnum's are", "download from :type url: str|unicode :param destination: target path and filename for downloaded", "in which sheets should be inserted into which table in which schema. Each", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp } }, {", "The above copyright notice and this permission notice shall be included in all", "progress indicator --print-queries Print queries immediately before execution Automatically turns off the progress", "'\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.time_stamp", "NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "(__docname__, __version__, __release__)) return 1 #/* ======================================================================= */# #/* Define dms2dd() function #/*", "method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS to", "as follows: 1. Get an ID 2. Get a set of field maps", "== uid: # The first instance goes into the table specified in the", "query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return", "#/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation", "'--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help', '-help', '--h', '-h'): return print_help()", "already exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map,", "process_subsample) # Exit if any problems were encountered if bail: return 1 #/*", "limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "names from an XLRD sheet object :param sheet: XLRD sheet object :type sheet:", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #", "maps and assemble an insert query 4. Execute the insert statement 5. Repeat", "'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name':", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED',", "keys and rows as values row The current row being processed - structured", "size and unit - perform conversion else: multipliers = { 'F': 1, 'FE':", "Don't need to process the reportnum information since it was added to the", "#/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema':", "callable object specified in map_def['processing']['function'] is responsible for ALL queries. The processing functions", "return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function #/* ======================================================================= */# def", "the default credentials and settings if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s'", "None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping", "{ 'Column1': 'Row 3 Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even more", "+= 2 process_subsample = args[i - 1] elif arg == '--subsample-min': i +=", "if isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\", '\"') # Single quotes", "count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts}", "*/# #/* Define _coord_formatter() protected static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs):", "output = [] columns = column_names(sheet) for r in range(1, sheet.nrows): # Skip", "Define affected_area() static method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None)", "======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database connection string", ":type destination: str|unicode :param overwrite: specify whether or not an existing destination should", "flag that requires parameters but the user did not supply the parameter #", "parse if arg_error: bail = True print(\"ERROR: Did not successfully parse arguments\") #", "in the target table, skip everything else _schema, _table = db_map.split('.') if not", "public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes around the table name. {", "8, 2014' __author__ = '<NAME>' __source__ = 'https://github.com/SkyTruth/scraper' __docname__ = basename(__file__) __license__ =", "a Postgres supported connection string. All other --db-* options are ignored. --db-host Hostname", "\"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* -----------------------------------------------------------------------", "Callable object responsible for additional sub-processing 'args': { # Essentially kwargs 'Arg1': parameter,", "downloaded file is not going to be accidentally deleted if download_file and not", "dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url,", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define main()", "#/* ======================================================================= */# #/* Define print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\"", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "existance test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor'", "was added to the initial query above if map_def['db_field'] == db_seqnos_field: query_fields =", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "======================================================================= */# def print_version(): \"\"\" Print script version information :return: 1 for exit", "map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error validating the field map if validate_field_map_error:", "#/* ----------------------------------------------------------------------- */# # Loops: # Get a report number to process #", "= args[i - 1] elif arg == '--db-pass': i += 2 db_pass =", "the input file will be downloaded to If used in conjunction with --no-download", "(None, '', u'') for iv in illegal_vals: if iv in (degrees, minutes, seconds,", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */#", "= value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "[] columns = column_names(sheet) for r in range(1, sheet.nrows): # Skip first row", "for db_map in field_map_order: # Check each field definition in the set of", "------{1} {2} \"\"\".format(__docname__, '-' * len(__docname__), main.__doc__)) return 1 #/* ======================================================================= */# #/*", "existing destination should be overwritten :type overwrite: bool :return: path to downloaded file", "with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB connection and turn on", ":param overwrite: specify whether or not an existing destination should be overwritten :type", "exit code purposes :rtype: int \"\"\" print(\"\"\" Help: {0} ------{1} {2} \"\"\".format(__docname__, '-'", "Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string = None db_host = 'localhost'", "NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def", "by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before doing any transformations, a set of SEQNOS/reportnum's", "%s;\"\"\" % schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/*", "'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table':", "Assumed mistyping of 'MI' 'UN': 0.0833333, # Assumed mistyping of 'IN' 'YARDS': 3", "(overwrite_downloaded_file, file_to_process)) # Make sure the user has write permission to the target", "final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' '", "3 Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\" Example Output: [ {", "} }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "information #/* ======================================================================= */# __version__ = '0.1-dev' __release__ = 'August 8, 2014' __author__", "name functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static", "SkyTruth Permission is hereby granted, free of charge, to any person obtaining a", "variable except IndexError: i += 1 arg_error = True print(\"ERROR: An argument has", "# Test connection print(\"Connecting to DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string)", "classes so we don't have to # have the same existance test for", "db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else: # Get the row for", "result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function #/*", "value value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/*", "uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field,", "- update user if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup", "urllib2.URLError, e: print(\"ERROR: Could not download from URL: %s\" % download_url) print(\" URLLIB", "Postgres Error: %s\" % e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download the", "all sheets containing the reportnum uid The current SEQNOS/reportnum being processed workbook XLRD", "Establish a DB connection and turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "statement 5. Repeat steps 2-4 until all tables have been processed Example bare", "bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM", "workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a DB", "iv in (degrees, minutes, seconds, quadrant): raise ValueError(\"ERROR: Illegal value: %s\" % iv)", "currently returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static", "rows:\") for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' '", "BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly to", "one table for db_map in field_map_order: query_fields = [] query_values = [] #", "('--usage', '-usage'): return print_usage() elif arg in ('--version', '-version'): return print_version() elif arg", "setup #/* ======================================================================= */# if sys.version[0] is 2: range = xrange #/* =======================================================================", "= kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently only", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function':", "if execute_queries: db_cursor.execute(query) # This processing function handled ALL inserts - tell parent", "% dirname(file_to_process)) # Handle subsample if process_subsample is not None: try: process_subsample =", "'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "}, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", "arg parser did not properly iterate the 'i' variable except IndexError: i +=", "execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/*", "use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "======================================================================= */# #/* Define print_version() function #/* ======================================================================= */# def print_version(): \"\"\" Print", "SkyTruth # # Permission is hereby granted, free of charge, to any person", "elif arg == '--subsample': i += 2 process_subsample = args[i - 1] elif", "for an argument # 3. The arg parser did not properly iterate the", "download_url = args[i - 1] elif arg == '--file-to-process': i += 2 file_to_process", "functions something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static method", "= {} for sname in workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict", "hereby granted, free of charge, to any person obtaining a copy of this", "METERS\" # This function takes care of that but must still supply the", "with something better. # Perhpas have a report_exists method on each of the", "incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\"", "from one of the workbook's sheets. The default column in 'CALLS' but can", "file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download from URL: %s\" % download_url)", "to DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as", "*/# #/* Add this field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", ":return: 0 on success and 1 on error :rtype: int \"\"\" #/* -----------------------------------------------------------------------", "target database [default: localhost] --db-user Username used for database connection [default: current user]", "Row 2 Values' } { 'Column1': 'Row 3 Val', 'Column2': 'Another Row 3", "to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class #/*", "} ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "{ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\"", "Handle NULL values - these should be handled elsewhere so this is more", "schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map()", "e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value", "return 1 #/* ======================================================================= */# #/* Define print_version() function #/* ======================================================================= */# def", "- Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final return #/* ----------------------------------------------------------------------- */#", "in workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] =", "+= 2 db_name = args[i - 1] elif arg == '--db-pass': i +=", "} ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "column in sheet_name, 'processing': { # Optional - should be set to None", "return destination #/* ======================================================================= */# #/* Define name_current_file() function #/* ======================================================================= */# def", "this software and associated documentation files (the \"Software\"), to deal in the Software", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "heavy lifting. Field maps are grouped by table and center around the target", "sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes around the", "in range(1, sheet.nrows): # Skip first row since it contains the header output.append(dict((columns[c],", "the progress indicator --print-queries Print queries immediately before execution Automatically turns off the", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "# Single quotes cause problems on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']]", "function must do more of the heavy lifting. Field maps are grouped by", "'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url =", "method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */#", "flags: --help More detailed description of this utility --usage Arguments, parameters, flags, options,", "which the row was extracted as described in the field map sheet_seqnos_field The", "None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'name', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "% (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if not results: validate_field_map_error", "takes care of that but must still supply the expected post-normalization format if", "function #/* ======================================================================= */# def print_help_info(): \"\"\" Print a list of help related", "fields in the NRC spreadsheet do not map directly to a column in", "ALL occurrences are sent to a different table - specified in the field", "Implement - check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid',", "sublicense, and/or sell copies of the Software, and to permit persons to whom", "Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/*", "instance goes into the table specified in the field map # This query", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, } }, { 'db_table': '\"BotTaskStatus\"', 'db_field':", "int :param quadrant: coordinate quadrant (N, E, S, W) :type quadrant: str|unicode :return:", "None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema':", "method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/*", "the initial query above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values =", "not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source: %s -> %s.%s\"", "row by row, a set of field map definitions are declared to describe", "all queries internally it can return '__NO_QUERY__' in order to be excluded from", "'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { # TODO: Implement", "args[i - 1] elif arg == '--subsample-min': i += 2 process_subsample_min = args[i", "notice and this permission notice shall be included in all copies or substantial", "xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet :return: list of elements, each containing one row of", "workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date a Postgres supported timestamp", "an int: %s\" % process_subsample) # Exit if any problems were encountered if", "urllib2 import psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */# #/* Python setup", "('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific values if isinstance(value, str)", "'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO:", "degrees :param degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes :type", "*/# #/* Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor']", "kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] raw_sheet_cache = kwargs['raw_sheet_cache']", "platform_letter(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "table, 'db_field': Name of target field, 'db_field_width': Maximum width for this field -", "sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE',", "DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage() function #/*", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with", "2 db_name = args[i - 1] elif arg == '--db-pass': i += 2", "the database db_write_mode The first part of the SQL statement for writes (e.g.", "======================================================================= */# def print_usage(): \"\"\" Command line usage information :return: 1 for exit", "already exists, in the target table, skip everything else _schema, _table = db_map.split('.')", "reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if necessary", "the field map # This query must be handled by the parent process", ":type field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table", "db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate parameters #/* ----------------------------------------------------------------------- */# bail =", "if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single field map to", "current SEQNOS/reportnum being processed workbook XLRD workbook object The callable object specified in", "#/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs): \"\"\" Convert coordinates from DMS to DD", "#/* Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the output", "Software without restriction, including without limitation the rights to use, copy, modify, merge,", "sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample = None process_subsample_min", "\"temporary\" NRC incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost", "#/* Parse arguments #/* ----------------------------------------------------------------------- */# i = 0 arg_error = False while", "mappings for map_def in field_map[db_map]: # Attempt to get the sheet to test", "'.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor,", "'\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, {", "{ # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "do if value == '' or unit == '': return db_null_value # Found", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME',", "options, etc. --version Version and ownership information --license License information \"\"\") return 1", "function itself handles all queries internally it can return '__NO_QUERY__' in order to", "*/# @staticmethod def areaid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value',", "*/# #/* Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an", "[ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing':", "#/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs): # TODO: Implement - currently returning NULL", "* FROM %s.%s WHERE %s = %s\"\"\" % (schema, table, field, reportnum)) return", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement - currently", "to the normal sheet cache, but with a list of rows instead of", "'Another Row 2 Val', 'Column3': 'Even more Row 2 Values' } { 'Column1':", "schema.table :rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query)", "# Prep workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook:", "#/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "# Optional - should be set to None if not used 'function': Callable", "the Software, and to permit persons to whom the Software is # furnished", "----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\"", "'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function':", "'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude',", "print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode = kwargs['db_write_mode'] uid", "workbook_datemode: int :return: date capable of being inserted into Postgres timestamp field :rtype:", "ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */# #", "'function': NrcParsedReportFields.areaid } }, { # TODO: Implement - check notes about which", "*/# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet do not map", "def print_usage(): \"\"\" Command line usage information :return: 1 for exit code purposes", "exit code purposes :rtype: int \"\"\" print(\"\"\" %s version %s - released %s", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE',", "= len(unique_report_ids) uid_i = 0 # Loop through the primary keys for uid", "======================================================================= */# def print_help(): \"\"\" Detailed help information :return: 1 for exit code", "'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id }", "if not results: validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host,", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' #/*", "'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } },", "credentials and settings if db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\"", ":rtype: list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/* ======================================================================= */# #/*", "center around the target field. There should be one map for every field", "notice shall be included in all copies or substantial portions of the Software.", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field':", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "This currently only reads rows from the sheet specified in the field map", "Row 1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\"", "Implement - check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter',", "value.replace(\"'\", '\"') # Single quotes cause problems on insert try: if e_map_def['db_field_width']: value", "and NOT the extra field maps # specified in the processing args. Currently", "1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084,", "sub-processing 'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } },", "Define print_license() function #/* ======================================================================= */# def print_license(): \"\"\" Print out license information", "= 0 # User feedback settings print_progress = True print_queries = False execute_queries", "% (__docname__, __version__, __release__)) return 1 #/* ======================================================================= */# #/* Define dms2dd() function", "URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries] {1}", "NRC spreadsheet do not map directly to a column in the database. These", "Specifies whether or not queries should be printed as they are executed raw_sheet_cache", "'Column2': 'Another Row 1 Val', 'Column3': 'Even More Row 1 Values' }, {", "executed raw_sheet_cache Structured similar to the normal sheet cache, but with a list", "#/* ======================================================================= */# def print_usage(): \"\"\" Command line usage information :return: 1 for", "value from the sheet and add to the query if row is not", "psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return: number of rows in the", "e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query)", "being processed, the bare minimum field map example below states that whatever value", "downloaded to If used in conjunction with --no-download it is assumed that the", "Can't find source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not", "reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define timestamp2datetime() function #/*", "kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value']", "return db_null_value # Found a sheen size and unit - perform conversion else:", "stamp: timestamp from XLRD reading a date encoded field :type stamp: float :param", "'column': Name of source column in sheet_name, 'processing': { # Optional - should", "#/* Cleanup and final return #/* ----------------------------------------------------------------------- */# # Update user padding =", "i += 1 print_queries = True print_progress = False elif arg == '--no-execute-queries':", "The latitude() and longitude() methods require the same general logic. \"\"\" try: row", "{ 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name':", "test_skytruth --db-user `whoami` --db-host localhost \"\"\" from __future__ import division from __future__ import", "Val\",\"Even More Row 3 Values\" Example Output: [ { 'Column1': 'Row 1 Val',", "method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */#", "======================================================================= */# #/* Define print_help() function #/* ======================================================================= */# def print_help(): \"\"\" Detailed", "*/# #/* Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param", "this value is # returned at the very end if initial_value_to_be_returned is None:", "'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"',", "# Assemble query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put", "#/* Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert", "logic. \"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec", "*/# @staticmethod def platform_letter(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value',", "return '__NO_QUERY__' in order to be excluded from the insert statement for that", "tell parent process there's nothing left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */#", "'DESCRIPTION_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "sheet as a dictionary :rtype: dict \"\"\" output = [] columns = column_names(sheet)", "instead of a dictionary containing reportnums as keys and rows as values row", "*/# field_map_order = ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table':", ":return: date capable of being inserted into Postgres timestamp field :rtype: str|unicode \"\"\"", "= True print_progress = False elif arg == '--no-execute-queries': i += 1 execute_queries", "test fails try: value = float(value) except ValueError: value = '' # No", "map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache,", "unique_report_ids: # Update user uid_i += 1 if print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\"", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "= None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] #", "the 'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing.", "% db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError as e: print(\"ERROR: Could", "specific function must do more of the heavy lifting. Field maps are grouped", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing':", "datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/*", "use for NULL db_seqnos_field The reportnum field in the database db_write_mode The first", "was wroking unique_report_ids = [i for i in unique_report_ids if i > 1074683]", "below states that whatever value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can", "----------------------------------------------------------------------- */# # Loops: # Get a report number to process # Get", "{0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1}", "directly to a column in the database. These fields require an additional processing", "return 1 #/* ======================================================================= */# #/* Define print_help_info() function #/* ======================================================================= */# def", "All field maps with keys set to schema.table db_cursor The cursor to be", "NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "a Postgres supported timestamp :param stamp: timestamp from XLRD reading a date encoded", "#/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download a file :param url:", ":type map_def: :rtype: :return: \"\"\" # TODO: Use 24 hour time workbook =", "field - used in string slicing 'db_schema': Name of target schema, 'sheet_name': Name", "= kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache =", "is responsible for ALL queries. The processing functions are intended to return a", "been processed Example bare minimum field map: The field map below shows that", "print_queries Specifies whether or not queries should be printed as they are executed", "print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and final return #/*", "db_null_value # Found a sheen size and unit - perform conversion else: multipliers", "2. Get a set of field maps for one target table 3. Process", "kwargs 'Arg1': parameter, 'Arg2': ... } } }, ], 'TABLE_NAME': [ { 'db_table':", "if value not in (None, '', u'', db_null_value): if isinstance(value, str) or isinstance(value,", "grab the value from the sheet and add to the query if row", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing':", "definitions are declared to describe which fields in which sheets should be inserted", "Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an", "wroking unique_report_ids = [i for i in unique_report_ids if i > 1074683] unique_report_ids.sort()", "dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count() function #/* ======================================================================= */#", "reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */#", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */#", "specified in the field map # This query must be handled by the", "NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public',", "document sheet by sheet and row by row, a set of field map", "supported timestamp :param stamp: timestamp from XLRD reading a date encoded field :type", "'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, ],", "degrees :type degrees: int :param minutes: coordinate minutes :type minutes: int :param seconds:", "getpass import os from os.path import * import sys import urllib2 import psycopg2", "False while i < len(args): try: arg = args[i] # Help arguments if", "Cache initial DB row counts for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts", "methods require converting a timestamp to a Postgres supported timestamp format. This method", "\"\"\" Convert coordinates from DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */#", "= kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet =", "st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/*", "%s\" % quadrant) output = int(degrees) + int(minutes) / 60 + int(seconds) /", "* import sys import urllib2 import psycopg2 import psycopg2.extras import xlrd #/* =======================================================================", "return NrcParsedReportFields._coord_formatter(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define longitude() static method #/* ----------------------------------------------------------------------- */#", "'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.status, } },", "#/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude() methods require", "if map_def['processing'] is None: try: value = row[map_def['column']] except KeyError: # UID doesn't", "there's nothing left to do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url()", "__release__)) return 1 #/* ======================================================================= */# #/* Define dms2dd() function #/* ======================================================================= */#", "of this software and associated documentation files (the \"Software\"), to deal in the", "#/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] }", "{'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS',", "print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not", "elif arg == '--db-pass': i += 2 db_pass = args[i - 1] #", "...\") for db_map in field_map_order: # Check each field definition in the set", "handle the normalization by reading from a field containing \"1.23 METERS\" # This", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None },", "uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field)", "Name of target field, 'db_schema': Name of target schema, 'sheet_name': Name of source", "query initial_value_to_be_returned = None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values =", "output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output #/* ======================================================================= */# #/*", "5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping of 'MI' 'UN':", "file. Unless the user is specifying a specific target for the download, this", "unit == '': return db_null_value # Found a sheen size and unit -", "'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime } }, { 'db_table':", "don't have to # have the same existance test for all tables if", "= \"SELECT * FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'", "main(args): \"\"\" Main routine to parse, transform, and insert Current.xlsx into the tables", "expecting to handle the normalization by reading from a field containing \"1.23 METERS\"", "+= 1 arg_error = True print(\"ERROR: Invalid argument: %s\" % arg) # This", "[default: localhost] --db-user Username used for database connection [default: current user] --db-name Name", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "field maps for one target table 3. Process all field maps and assemble", "if unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()] * value) + '", "#/* ======================================================================= */# #/* Define db_row_count() function #/* ======================================================================= */# def db_row_count(cursor, schema_table):", "until all tables have been processed Example bare minimum field map: The field", "unicode): # Having single quotes in the string causes problems on insert because", "#/* ======================================================================= */# #/* Commandline Execution #/* ======================================================================= */# if __name__ == '__main__':", "'s', 'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output = int(degrees) +", "exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \",", "*/# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several", "sheets ...\") sheet_cache = {} raw_sheet_cache = {} for sname in workbook.sheet_names(): if", "value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries,", "'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not", "'w'): raise ValueError(\"ERROR: Invalid quadrant: %s\" % quadrant) output = int(degrees) + int(minutes)", "i += 1 download_file = False elif arg == '--download-url': i += 2", "NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static", "i += 2 db_pass = args[i - 1] # Commandline print-outs elif arg", "maps for one table for db_map in field_map_order: query_fields = [] query_values =", "{ 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help', '-help', '--h', '-h'):", "table, 'db_field': Name of target field, 'db_schema': Name of target schema, 'sheet_name': Name", "to process for map_def in field_map[db_map]: # Don't need to process the reportnum", "query, but not if the report already exists query = \"\"\"%s %s (%s)", "@staticmethod def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries", "the processing args. Currently not a problem since # Build query initial_value_to_be_returned =", "happens. Field maps using additional processing always receive the following kwargs: all_field_maps All", ":rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL] {1} [--db-connection-string]", "--no-print-progress Don't print the progress indicator --print-queries Print queries immediately before execution Automatically", "raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/* =======================================================================", "unique report id's unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems(): for reportnum", "#/* Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in", "DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered an error", "'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"'] #/* ----------------------------------------------------------------------- */# #/* Parse arguments #/* ----------------------------------------------------------------------- */# i =", "# Done processing - update user if print_progress: print(\" - Done\") #/* -----------------------------------------------------------------------", "----------------------------------------------------------------------- */# #/* Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs):", "= False elif arg == '--download-url': i += 2 download_url = args[i -", "NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public',", "----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */# @staticmethod def platform_letter(**kwargs):", "must be handled by the parent process so this value is # returned", "= 'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field", "to test except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not exist: %s\"", "'Row 2 Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even more Row 2", "processing. Rather than process the input document sheet by sheet and row by", "db_host = args[i - 1] elif arg == '--db-user': i += 2 db_user", "first row since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in", "function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook", "'function': NrcScrapedReportFields.materials_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS',", "for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] # Found a", "f: f.write(response.read()) return destination #/* ======================================================================= */# #/* Define name_current_file() function #/* =======================================================================", "doesn't appear in the specified sheet - populate a NULL value value =", "overwrite: specify whether or not an existing destination should be overwritten :type overwrite:", "database [default: localhost] --db-user Username used for database connection [default: current user] --db-name", "Example Output: [ { 'Column1': 'Row 1 Val', 'Column2': 'Another Row 1 Val',", "with the query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'],", "# # Permission is hereby granted, free of charge, to any person obtaining", "all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_write_mode = kwargs['db_write_mode'] print_queries = kwargs['print_queries'] execute_queries", "each field definition in the set of mappings for map_def in field_map[db_map]: #", "software and associated documentation files (the \"Software\"), to deal in the Software without", "process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache,", "* value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method", "and not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download target", "if the report already exists query = \"\"\"%s %s (%s) VALUES (%s);\"\"\" \\", "row sheet The entire sheet from which the row was extracted as described", "----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */# # Loops: # Get a", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "}, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "incident spreadsheet Sample command: ./bin/nrcSpreadsheetScraper.py --db-name test_skytruth --db-user `whoami` --db-host localhost \"\"\" from", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "#/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping ...\") for db_map in", "the following kwargs: all_field_maps All field maps with keys set to schema.table db_cursor", "\"\"\" Download a file :param url: URL to download from :type url: str|unicode", "the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "a DB connection and turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit =", "int \"\"\" print(\"\"\" Help flags: --help More detailed description of this utility --usage", "\"\"\") return 1 #/* ======================================================================= */# #/* Define print_version() function #/* ======================================================================= */#", "'db_field': 'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype }", "= cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function #/* =======================================================================", "# Make sure schema and table exist in the DB query = \"SELECT", "= { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'CALLS',", "routine to parse, transform, and insert Current.xlsx into the tables used by the", "options are ignored. --db-host Hostname for the target database [default: localhost] --db-user Username", "3 Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even more Row 3 Values'", "#/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs):", "areaid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "== '--download-url': i += 2 download_url = args[i - 1] elif arg ==", "string causes problems on insert because the entire # value is single quoted", "map_def['db_table'], map_def['db_field'])) # Encountered an error validating the field map if validate_field_map_error: db_cursor.close()", "steps 2-4 until all tables have been processed Example bare minimum field map:", "args[i - 1] elif arg == '--db-host': i += 2 db_host = args[i", "= '' db_write_mode = 'INSERT INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field", "update user if print_progress: print(\" - Done\") #/* ----------------------------------------------------------------------- */# #/* Cleanup and", "in a table. The structure for field maps is roughly as follows: All", "{ # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "of target table, 'db_field': Name of target field, 'db_schema': Name of target schema,", "in input file, 'column': Name of source column in sheet_name, 'processing': { #", "unit - perform conversion else: multipliers = { 'F': 1, 'FE': 1, 'FEET':", "'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'}", "quadrant: coordinate quadrant (N, E, S, W) :type quadrant: str|unicode :return: decimal degrees", "count in initial_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding -", "FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "or isinstance(value, unicode): # Having single quotes in the string causes problems on", "all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/*", "no additional processing is required, simply grab the value from the sheet and", "#/* ======================================================================= */# #/* Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode,", "----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs):", "--no-download it is assumed that the specified file already exists and should be", "== '--subsample-min': i += 2 process_subsample_min = args[i - 1] # Positional arguments", "] } } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name':", "field map definitions are declared to describe which fields in which sheets should", "subject to the following conditions: # # The above copyright notice and this", "value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/*", "'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public',", ":rtype: float \"\"\" illegal_vals = (None, '', u'') for iv in illegal_vals: if", "= map_def['processing']['function'](db_cursor=db_cursor, uid=uid, workbook=workbook, row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries,", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "sheet_cache = {} raw_sheet_cache = {} for sname in workbook.sheet_names(): if sname not", "be used for processing [default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries", "NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table':", "#/* Value goes from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if", "Define column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the ordered", "conversion else: multipliers = { 'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333,", "map_def in field_map[db_map]: # Don't need to process the reportnum information since it", "value: value = db_null_value # Assemble query if value not in ('__NO_QUERY__', db_null_value):", "status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/* -----------------------------------------------------------------------", "2 Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More", "a list of rows, each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row", "'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None },", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "and drive processing. Rather than process the input document sheet by sheet and", "----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process) try:", "\"\"\" Get the ordered column names from an XLRD sheet object :param sheet:", "{ # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, { 'db_table':", "db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single field map", "to provide better organization and to prevent having to name functions something like:", "is hereby granted, free of charge, to any person obtaining a copy #", "in the 'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional", "public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that a specific function must do", "kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache']", "supported timestamp format. This method eliminates repitition :param workbook: :type workbook: :param row:", "elif arg == '--download-url': i += 2 download_url = args[i - 1] elif", "+= 2 db_user = args[i - 1] elif arg == '--db-name': i +=", "(indent, schema_table + ' ' * (padding - len(schema_table) + 4), count)) print(\"New", "put quotes around specific values if isinstance(value, str) or isinstance(value, unicode): # Having", "for i in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min +", "*/# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "follows: 1. Get an ID 2. Get a set of field maps for", "field map: The field map below shows that the value in the 'RESPONSIBLE_COMPANY'", "processed Example bare minimum field map: The field map below shows that the", "'db_table': Name of target table, 'db_field': Name of target field, 'db_schema': Name of", "the sheet specified in the field map and NOT the extra field maps", "schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent, schema_table + ' ' * (padding", "Value goes from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing']", "\"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field Maps #/* ----------------------------------------------------------------------- */# field_map_order =", "URL from which to download the input file --no-download Don't download the input", "into Postgres timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter)", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "minimum field map: The field map below shows that the value in the", "# Sheet was empty pass # Get a list of unique report id's", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC", "# Get a list of unique report id's unique_report_ids = [] for s_name,", "db_write_mode = kwargs['db_write_mode'] uid = kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None", "date capable of being inserted into Postgres timestamp field :rtype: str|unicode \"\"\" dt", "to the initial query above if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values", "= kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return timestamp2datetime(row[map_def['column']], workbook.datemode) #/* -----------------------------------------------------------------------", "}, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name':", "skip everything else _schema, _table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table):", "'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { # TODO: Implement -", "a field map to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i =", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */# #/*", "problems on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\"", "# The MIT License (MIT) # # Copyright (c) 2014 SkyTruth # #", "set of field maps for one target table 3. Process all field maps", "if isinstance(value, str) or isinstance(value, unicode): # Having single quotes in the string", "XLRD reading a date encoded field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode", "+ 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts and destroy DB", "----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database is expecting \"\"\" map_def = kwargs['map_def']", "writes (e.g. INSERT INTO) execute_queries Specifies whether or not queries should actually be", "uid The current SEQNOS/reportnum being processed workbook XLRD workbook object The callable object", "# 2. The arg parser did not properly consume all parameters for an", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { # TODO: Implement -", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "this is more of a safety net if value is None or not", "#/* Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see", "specified in the field map arguments for e_db_map in extras_field_maps: for e_map_def in", "'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema': 'public',", "None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "and XLRD workbook for processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to", "\"\"\" map_def = kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if value ==", "#/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet do", "'LOCATION_ZIP', 'processing': None }, { # TODO: Implement - check notes about which", "Version and ownership information --license License information \"\"\") return 1 #/* ======================================================================= */#", "'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example", "Row 2 Val', 'Column3': 'Even more Row 2 Values' } { 'Column1': 'Row", "Row 2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even More Row 3 Values\"", "populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None", "def time_stamp(**kwargs): \"\"\" Required to insert a NULL value \"\"\" return kwargs.get('db_null_value', None)", "return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */#", "1] # Positional arguments and errors else: # Invalid argument i += 1", "called in the return statement \"\"\" return NrcScrapedReportFields._datetime_caller(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define", "NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly to", "u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\", '\"') #", "#/* ----------------------------------------------------------------------- */# #/* Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error =", "raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is properly quoted if value not", "cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\" % (schema, table, field, reportnum))", "minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds :type seconds: int", "#/* Define process_field_map() function #/* ======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid", "input file --overwrite-download If the --file-to-process already exists and --no-download has not been", "#/* Define print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\" Print a list", "' ' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success", "this flag is not needed due the default file name containing datetime down", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': {", "dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/* Validate", "%s\" % map_def['sheet_name']) # Make sure schema and table exist in the DB", "the user has write permission to the target directory if not os.access(dirname(file_to_process), os.W_OK):", "'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name':", "field, reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define timestamp2datetime() function", "'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement -", "*/# def print_version(): \"\"\" Print script version information :return: 1 for exit code", "= args[i - 1] # Commandline print-outs elif arg == '--no-print-progress': i +=", "value is # returned at the very end if initial_value_to_be_returned is None: initial_value_to_be_returned", "in all sheets containing the reportnum uid The current SEQNOS/reportnum being processed workbook", "method #/* ----------------------------------------------------------------------- */# @staticmethod def blockid(**kwargs): # TODO: Implement - currently returning", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "bail = True print(\"ERROR: Did not successfully parse arguments\") # Make sure the", "connection is now set to autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */#", "= ['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "definition contains all of the additional arguments and information necessary to execute one", "\"\"\" Convert a float formatted date a Postgres supported timestamp :param stamp: timestamp", "print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is properly quoted if", "whom the Software is # furnished to do so, subject to the following", "----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* -----------------------------------------------------------------------", "== db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else: # Get the row", "'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG',", "int :return: date capable of being inserted into Postgres timestamp field :rtype: str|unicode", "None for row in raw_sheet_cache[map_def['sheet_name']]: extra_query_fields = [] extra_query_values = [] # Found", "columns = column_names(sheet) for r in range(1, sheet.nrows): # Skip first row since", "*/# #/* Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name): \"\"\" Generate the", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "%s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/* -----------------------------------------------------------------------", "WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT *", "or not queries should be printed as they are executed raw_sheet_cache Structured similar", "sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function", "exist in the DB query = \"SELECT * FROM information_schema.columns WHERE table_schema =", "obtaining a copy of this software and associated documentation files (the \"Software\"), to", "return 1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if", "{ 'function': NrcScrapedMaterialFields.st_id } } ] } } } }, { 'db_table': '\"NrcScrapedReport\"',", "value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_length',", "map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet):", "process_subsample < len(unique_report_ids): # TODO: Delete constraining line - needed to verify everything", "input document sheet by sheet and row by row, a set of field", "kwargs['reportnum'] cursor = kwargs['db_cursor'] table = kwargs['table'] field = kwargs.get('field', 'reportnum') schema =", "print_license() function #/* ======================================================================= */# def print_license(): \"\"\" Print out license information :return:", "*/# class NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map", "OTHER DEALINGS IN THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage() function", "map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* =======================================================================", "print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define NrcScrapedReportField() class", "shows that no specific column contains the value required for public.\"NrcParsedReport\".longitude Instead, some", "returning NULL return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method", "None db_host = 'localhost' db_name = 'skytruth' db_user = getpass.getuser() db_pass = ''", "Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the", "{ 'public.\"NrcScrapedReport\"': [ { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "are grouped by table and center around the target field. There should be", "'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL':", "set of mappings for map_def in field_map[db_map]: # Attempt to get the sheet", "% (overwrite_downloaded_file, file_to_process)) # Make sure the user has write permission to the", "table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing':", ":type overwrite: bool :return: path to downloaded file :rtype: str|unicode \"\"\" # Validate", "require \"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value =", "column contains the value required for public.\"NrcParsedReport\".longitude Instead, some information must be passed", "method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation \"\"\"", "__future__ import print_function from __future__ import unicode_literals from datetime import datetime import getpass", "The order of operations for a given ID is as follows: 1. Get", "i += 2 download_url = args[i - 1] elif arg == '--file-to-process': i", "{ 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None", "be handled elsewhere so this is more of a safety net if value", "for one table for db_map in field_map_order: query_fields = [] query_values = []", "arg in ('--license', '-usage'): return print_license() # Spreadsheet I/O elif arg == '--no-download':", "# No sheen size - nothing to do if value == '' or", "*/# # Database db_connection_string = None db_host = 'localhost' db_name = 'skytruth' db_user", "the table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name':", "c)) for c in range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define report_exists()", "sheet_dict} except IndexError: # Sheet was empty pass # Get a list of", ":type seconds: int :param quadrant: coordinate quadrant (N, E, S, W) :type quadrant:", "for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */#", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "all sheets needed by the field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache", "value is not a float, change it to nothing so the next test", "return 1 #/* ======================================================================= */# #/* Define dms2dd() function #/* ======================================================================= */# def", "furnished to do so, subject to the following conditions: # # The above", "Values' } { 'Column1': 'Row 3 Val', 'Column2': 'Another Row 3 Val', 'Column3':", "row[map_def['column']] except KeyError: # UID doesn't appear in the specified sheet - populate", "to nothing so the next test fails try: value = float(value) except ValueError:", "'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema':", "BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields in the NRC", "row: :param map_def: :type map_def: :rtype: :return: \"\"\" # TODO: Use 24 hour", "last argument is a flag that requires parameters but the user did not", "connection and turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor", "necessary if process_subsample is not None and process_subsample < len(unique_report_ids): # TODO: Delete", "sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) # Make sure the value is properly", "'\"BotTaskStatus\"', 'db_field': 'bot', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': BotTaskStatusFields.bot,", "======================================================================= */# #/* Define print_license() function #/* ======================================================================= */# def print_license(): \"\"\" Print", "for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_width, 'args': {'unit_field': 'SHEEN_SIZE_WIDTH_UNITS'} } }, { #", "in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a", "% e) return 1 #/* ----------------------------------------------------------------------- */# #/* Download the spreadsheet #/* -----------------------------------------------------------------------", "----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\" return 'http://nrc.uscg.mil/' #/* -----------------------------------------------------------------------", "'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "----------------------------------------------------------------------- */# #/* Define longitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def longitude(**kwargs):", "'__NO_QUERY__' in order to be excluded from the insert statement for that table.", "* (padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit", "in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field']) # Only put quotes around specific values if isinstance(value,", ":param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date capable of being inserted", "Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to", "this field map to the insert statement #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL", "constraining line - needed to verify everything was wroking unique_report_ids = [i for", "[options] [--no-download] [--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password]", "that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "and turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor =", "of column names :rtype: list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/*", "download from URL: %s\" % download_url) print(\" URLLIB Error: %s\" % e) return", "'column': None, 'processing': { 'function': NrcParsedReportFields.affected_area, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'county',", "sheet The entire sheet from which the row was extracted as described in", "DMS to DD \"\"\" return NrcParsedReportFields._coord_formatter(**kwargs) #/* ======================================================================= */# #/* Define NrcScrapedMaterialFields() class", "Row 2 Val\",\"Even More Row 2 Values\" \"Row 3 Val\",\"Another Row 3 Val\",\"Even", "map definition being processed (example below) print_queries Specifies whether or not queries should", "not exist: %s\" % map_def['sheet_name']) # Make sure schema and table exist in", "======================================================================= */# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook']", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,", "'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': { 'function': NrcScrapedReportFields.material_name, 'args': { 'extras_table': '\"NrcScrapedMaterial\"', 'extras_schema':", "# 1. The last argument is a flag that requires parameters but the", "Do something with the query query = \"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" %", "*/# validate_field_map_error = False print(\"Validating field mapping ...\") for db_map in field_map_order: #", ":rtype: int \"\"\" print(\"\"\" %s version %s - released %s \"\"\" % (__docname__,", "source column in sheet_name, 'processing': { # Optional - should be set to", "i += 2 process_subsample = args[i - 1] elif arg == '--subsample-min': i", "of the sheet as a dictionary :rtype: dict \"\"\" output = [] columns", "e) return 1 # Prep workbook print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process,", "from the sheet specified in the field map and NOT the extra field", "schema=_schema, table=_table): # Get a single field map to process for map_def in", "'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None },", "None) #/* ----------------------------------------------------------------------- */# #/* Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing':", "*/# if sys.version[0] is 2: range = xrange #/* ======================================================================= */# #/* Build", "\"Software\"), to deal in the Software without restriction, including without limitation the rights", "#/* Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO:", "quadrant): \"\"\" Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate", "'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed mistyping of 'MI'", "return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/* Define BotTaskStatusFields() class #/* ======================================================================= */#", "def status(**kwargs): return 'DONE' #/* ----------------------------------------------------------------------- */# #/* Define bot() static method #/*", "kwargs: all_field_maps All field maps with keys set to schema.table db_cursor The cursor", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] +=", "sheets. The default column in 'CALLS' but can be specified by the user.", "kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad])", "it can return '__NO_QUERY__' in order to be excluded from the insert statement", "----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs):", "i += 1 execute_queries = False # Additional options elif arg == '--overwrite-download':", "is not going to be accidentally deleted if download_file and not overwrite_downloaded_file and", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "in the specified sheet - populate a NULL value value = db_null_value #", "deal # in the Software without restriction, including without limitation the rights #", "connections # db_conn.commit() # connection is now set to autocommit db_cursor.close() db_conn.close() return", "INTO) execute_queries Specifies whether or not queries should actually be executed map_def Current", "class NrcParsedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly", "field in the database db_write_mode The first part of the SQL statement for", "- must be an int: %s\" % process_subsample) # Exit if any problems", "table_name = '%s' AND column_name = '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field'])", "final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts", "'SHEEN_SIZE_WIDTH_UNITS'} } }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public',", "'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with all options: This field", "so, subject to the following conditions: The above copyright notice and this permission", "Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments", "unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */# #", "main() function #/* ======================================================================= */# def main(args): \"\"\" Main routine to parse, transform,", "maps for one target table 3. Process all field maps and assemble an", "#/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* ======================================================================= */# #/*", "need to process the reportnum information since it was added to the initial", "'\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute", "'\"NrcScrapedReport\"', 'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime", "properly consume all parameters for an argument # 3. The arg parser did", "to use for NULL db_seqnos_field The reportnum field in the database db_write_mode The", "if value == '' or unit == '': return db_null_value # Found a", "print(\"Connecting to DB: %s\" % db_connection_string) try: connection = psycopg2.connect(db_connection_string) connection.close() except psycopg2.OperationalError", "If used in conjunction with --no-download it is assumed that the specified file", "}, :param args: arguments from the commandline (sys.argv[1:] in order to drop the", "encoded field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return:", "Get field maps for one table for db_map in field_map_order: query_fields = []", "the target directory if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema':", "conditions: The above copyright notice and this permission notice shall be included in", "Define latitude() static method #/* ----------------------------------------------------------------------- */# @staticmethod def latitude(**kwargs): \"\"\" Convert coordinates", "'\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None", "following kwargs: all_field_maps All field maps with keys set to schema.table db_cursor The", "the sheet and add to the query if row is not None: #/*", "map classes so we don't have to # have the same existance test", "conjunction with --no-download it is assumed that the specified file already exists and", "validate_field_map_error = False print(\"Validating field mapping ...\") for db_map in field_map_order: # Check", "as f: f.write(response.read()) return destination #/* ======================================================================= */# #/* Define name_current_file() function #/*", "directory if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write permission for", "arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return print_help_info() elif arg in ('--help', '-help',", "The MIT License (MIT) # # Copyright (c) 2014 SkyTruth # # Permission", "= True elif arg == '--subsample': i += 2 process_subsample = args[i -", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema':", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "}, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing':", "extra_query_values = [] # Found a matching row if row[sheet_seqnos_field] == uid: #", "'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': {", "except xlrd.XLRDError: validate_field_map_error = True print(\"ERROR: Sheet does not exist: %s\" % map_def['sheet_name'])", "#/* ----------------------------------------------------------------------- */# @staticmethod def areaid(**kwargs): # TODO: Implement - currently returning NULL", "be executed map_def Current map definition being processed (example below) print_queries Specifies whether", "single table to process # Get a field map to process print(\"Processing workbook", "1] elif arg == '--db-user': i += 2 db_user = args[i - 1]", "False # Make sure arguments were properly parse if arg_error: bail = True", "{ 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, :param", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None", "32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map", "'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company',", "# # The MIT License (MIT) # # Copyright (c) 2014 SkyTruth #", "'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public',", "field_map_order: # Check each field definition in the set of mappings for map_def", "of field maps for one target table 3. Process all field maps and", "sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError: row = None # If no", "output = dms2dd(row[col_deg], row[col_min], row[col_sec], row[col_quad]) except (ValueError, KeyError): output = kwargs['db_null_value'] return", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "this permission notice shall be included in all # copies or substantial portions", "sheen size and unit - perform conversion else: multipliers = { 'F': 1,", "+ process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data #/* ----------------------------------------------------------------------- */# # Loops:", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.platform_letter } }, { 'db_table': '\"NrcParsedReport\"',", "stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in", "ts) for ts in final_table_counts} for schema_table, count in final_db_row_counts.iteritems(): print(\"%s%s%s\" % (indent,", "field map example below states that whatever value is in sheet 'CALLS' and", "to a column in the database. These fields require an additional processing step", "+= 2 db_pass = args[i - 1] # Commandline print-outs elif arg ==", "{ 'function': NrcScrapedReportFields.ft_id } } ], 'public.\"NrcParsedReport\"': [ { 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum',", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "target path and filename for downloaded file :type destination: str|unicode :param overwrite: specify", "return print_version() elif arg in ('--license', '-usage'): return print_license() # Spreadsheet I/O elif", "string :type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return: number of", "Make sure arguments were properly parse if arg_error: bail = True print(\"ERROR: Did", "'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"',", "#/* Define bot() static method #/* ----------------------------------------------------------------------- */# @staticmethod def bot(**kwargs): return 'NrcExtractor'", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None },", "parameter, 'Arg2': ... } } }, ], 'TABLE_NAME': [ { 'db_table': Name of", "'column': 'TYPE_OF_INCIDENT', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name':", "below shows that the value in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet", "from __future__ import division from __future__ import print_function from __future__ import unicode_literals from", "the progress indicator --no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return", "'--print-queries': i += 1 print_queries = True print_progress = False elif arg ==", "function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to see if a report", "FROM %s.%s WHERE %s = %s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall())", "'--db-name': i += 2 db_name = args[i - 1] elif arg == '--db-pass':", "Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to", "== '--db-user': i += 2 db_user = args[i - 1] elif arg ==", "test for all tables if table=='\"BotTaskStatus\"': cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND", "processing is required, simply grab the value from the sheet and add to", "converters require \"\"\" row = kwargs['row'] map_def = kwargs['map_def'] db_null_value = kwargs['db_null_value'] value", "elif arg == '--db-name': i += 2 db_name = args[i - 1] elif", "copyright notice and this permission notice shall be included in all # copies", "the SQL statement for writes (e.g. INSERT INTO) execute_queries Specifies whether or not", "to the following conditions: The above copyright notice and this permission notice shall", "ownership information --license License information \"\"\") return 1 #/* ======================================================================= */# #/* Define", "workbook.sheet_by_name(map_def['sheet_name']) if map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source:", "Convert an XLRD sheet object into a list of rows, each structured as", "'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with all", "quadrant.lower() in ('s', 'w'): output *= -1 return output #/* ======================================================================= */# #/*", "'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI':", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [", "schema_table: schema.table :type schema_table: str|unicode :return: number of rows in the specified schema.table", "target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the user has write", "#/* ----------------------------------------------------------------------- */# #/* Define blockid() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "map arguments for e_db_map in extras_field_maps: for e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor,", "# Get the row for this sheet try: row = sheet_cache[map_def['sheet_name']][uid] except KeyError:", "*/# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\" Database", "args. Currently not a problem since # Build query initial_value_to_be_returned = None for", "#/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "--file-to-process already exists and --no-download has not been specified, blindly overwrite the file.", "======================================================================= */# def column_names(sheet, formatter=str): \"\"\" Get the ordered column names from an", "# The first instance goes into the table specified in the field map", "#/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def", "'Column1': 'Row 2 Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even more Row", "# Could not get the sheet to test except xlrd.XLRDError: validate_field_map_error = True", "to insert a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/*", "one of the workbook's sheets. The default column in 'CALLS' but can be", "print(\"Opening workbook: %s\" % file_to_process) with xlrd.open_workbook(file_to_process, 'r') as workbook: # Establish a", "field in all sheets containing the reportnum uid The current SEQNOS/reportnum being processed", "try: value = row[map_def['column']] except KeyError: # UID doesn't appear in the specified", "file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download from URL:", "= True print_queries = False execute_queries = True final_table_counts = ['public.\"NrcParsedReport\"', 'public.\"NrcScrapedMaterial\"', 'public.\"NrcScrapedReport\"']", "print_usage() elif arg in ('--version', '-version'): return print_version() elif arg in ('--license', '-usage'):", "None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "*/# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See", "whatever value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY' can be sent to", "False download_file = True process_subsample = None process_subsample_min = 0 # User feedback", "'Arg1': parameter, 'Arg2': ... } } }, { 'db_table': Name of target table,", "- check notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema':", "= [] # Found a matching row if row[sheet_seqnos_field] == uid: # The", "try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail = True print(\"ERROR:", "should be handled elsewhere so this is more of a safety net if", "The entire sheet from which the row was extracted as described in the", "outfile exists: %s\" % (overwrite, destination)) # Download response = urllib2.urlopen(url) with open(destination,", "map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps = map_def['processing']['args']['extras_field_maps'] db_write_mode", "(schema, table, field, reportnum)) return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define", "= 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process", "Val\",\"Even More Row 1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row", "'Arg1': parameter, 'Arg2': ... } } }, ], 'TABLE_NAME': [ { 'db_table': Name", "validating the field map if validate_field_map_error: db_cursor.close() db_conn.close() return 1 #/* ----------------------------------------------------------------------- */#", "Output: [ { 'Column1': 'Row 1 Val', 'Column2': 'Another Row 1 Val', 'Column3':", "\"\"\" #/* ----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "*/# #/* Define report_exists() function #/* ======================================================================= */# def report_exists(**kwargs): \"\"\" Check to", "in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "'AMOUNT_OF_MATERIAL', 'processing': None }, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'unit',", "permanent archival :param input_name: input file name (e.g. Current.xlsx) :type input_name: str|unicode :return:", "a subsample if necessary if process_subsample is not None and process_subsample < len(unique_report_ids):", "'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public',", "for exit code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download]", "care of that but must still supply the expected post-normalization format if unit.upper()", "Invalid quadrant: %s\" % quadrant) output = int(degrees) + int(minutes) / 60 +", "return len(cursor.fetchall()) > 0 #/* ======================================================================= */# #/* Define timestamp2datetime() function #/* =======================================================================", "queries internally it can return '__NO_QUERY__' in order to be excluded from the", "for c in range(sheet.ncols))) return output #/* ======================================================================= */# #/* Define report_exists() function", "method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url()", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */#", "'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds':", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def st_id(**kwargs): return kwargs.get('db_null_value', None) #/* =======================================================================", "'column': None, 'processing': { 'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table':", "documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/*", "+ sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file = True process_subsample = None", "definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error = False print(\"Validating field mapping ...\") for db_map", "from __future__ import print_function from __future__ import unicode_literals from datetime import datetime import", "1 #/* ======================================================================= */# #/* Define print_help_info() function #/* ======================================================================= */# def print_help_info():", "1 for exit code purposes :rtype: int \"\"\" print(\"\"\" %s version %s -", "= { 'F': 1, 'FE': 1, 'FEET': 1, 'IN': 0.0833333, 'INCHES': 0.0833333, 'KILOMETERS':", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reached_water',", "% value) else: query_values.append(\"%s\" % value) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Execute query #/*", "of source column in sheet_name, 'processing': { # Optional - should be set", "#/* Define materials_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default", "'\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None }, {", "int :param minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds :type", "applied against each ID which means that if ID number 1234 is being", "_table = db_map.split('.') if not report_exists(db_cursor=db_cursor, reportnum=uid, schema=_schema, table=_table): # Get a single", "one of these processing functions. A class is used as a namespace to", "}, Example field map with all options: This field map shows that no", ":rtype: int \"\"\" query = \"\"\"SELECT COUNT(1) FROM %s;\"\"\" % schema_table cursor.execute(query) result", "\"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_width() static method #/* -----------------------------------------------------------------------", "= True print(\"ERROR: Invalid argument: %s\" % arg) # This catches three conditions:", "# Loop through the primary keys for uid in unique_report_ids: # Update user", "*/# #/* Build information #/* ======================================================================= */# __version__ = '0.1-dev' __release__ = 'August", "query_fields = [] query_values = [] # If the report already exists, in", "*/# #/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache all sheets needed by", "Overwrite=%s and download target exists: %s\" % (overwrite_downloaded_file, file_to_process)) # Make sure the", "if value == 'INC': value = 'INCIDENT' return value #/* ======================================================================= */# #/*", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY',", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "formatted name :rtype: str|unicode \"\"\" dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split =", "'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'NAME_OF_MATERIAL', 'processing': None }, { 'db_table':", "'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema': 'public', 'sheet_name':", "= 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file = False download_file", "INTO' db_seqnos_field = 'reportnum' db_null_value = 'NULL' sheet_seqnos_field = 'SEQNOS' # NRC file", "Software is # furnished to do so, subject to the following conditions: #", "= kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad =", "report id's unique_report_ids = [] for s_name, s_rows in sheet_cache.iteritems(): for reportnum in", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema':", "to do if value == '' or unit == '': return db_null_value #", "'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table':", "#/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for function called in", "all # copies or substantial portions of the Software. # # THE SOFTWARE", "1. The last argument is a flag that requires parameters but the user", "can return '__NO_QUERY__' in order to be excluded from the insert statement for", "= kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps =", "#/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs):", "abspath(args[i - 1]) # Database connection elif arg == '--db-connection-string': i += 2", "value = db_null_value # Assemble query if value not in ('__NO_QUERY__', db_null_value): query_fields.append(map_def['db_field'])", "Values' } ] :param sheet: XLRD sheet object from xlrd.open_workbook('workbook').sheet_by_name('name') :type sheet: xlrd.Sheet", "More Row 3 Values\" Example Output: [ { 'Column1': 'Row 1 Val', 'Column2':", "'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, {", "feedback settings print_progress = True print_queries = False execute_queries = True final_table_counts =", "'function': NrcParsedReportFields.ft_id, } } ], 'public.\"BotTaskStatus\"': [ { 'db_table': '\"BotTaskStatus\"', 'db_field': 'task_id', 'db_schema':", "given ID is as follows: 1. Get an ID 2. Get a set", "not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR: Need write permission for download directory:", "empty pass # Get a list of unique report id's unique_report_ids = []", "affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/*", "----------------------------------------------------------------------- */# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs):", "cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE bot='NrcExtractor' AND task_id = %s\"\"\" % (schema, table,", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedMaterialFields.st_id } } ] } } }", "for cell in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function #/* =======================================================================", "arguments and information necessary to execute one of these processing functions. A class", "= kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently only reads rows from", "(%s) VALUES (%s);\"\"\" \\ % (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries:", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema':", "the following conditions: # # The above copyright notice and this permission notice", "'Arg2': ... } } }, { 'db_table': Name of target table, 'db_field': Name", "needed to verify everything was wroking unique_report_ids = [i for i in unique_report_ids", "for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if", "table name. { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS',", "value = db_null_value #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "overwrite=False): \"\"\" Download a file :param url: URL to download from :type url:", "['public.\"NrcScrapedReport\"', 'public.\"NrcParsedReport\"','public.\"BotTaskStatus\"' ] field_map = { 'public.\"NrcScrapedReport\"': [ { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'reportnum',", "processing function handled ALL inserts - tell parent process there's nothing left to", "version information :return: 1 for exit code purposes :rtype: int \"\"\" print(\"\"\" %s", "The first part of the SQL statement for writes (e.g. INSERT INTO) execute_queries", "1 arg_error = True print(\"ERROR: An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */#", "to do so, subject to the following conditions: # # The above copyright", "'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field':", "every field in a table. The structure for field maps is roughly as", "i in field_map.keys()]) indent = \" \" * 2 print(\"Initial row counts:\") for", "table=_table): # Get a single field map to process for map_def in field_map[db_map]:", "*/# #/* Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields", "# 3. The arg parser did not properly iterate the 'i' variable except", "exist: %s\" % map_def['sheet_name']) # Make sure schema and table exist in the", "#/* Define Defaults #/* ----------------------------------------------------------------------- */# # Database db_connection_string = None db_host =", "All other --db-* options are ignored. --db-host Hostname for the target database [default:", "import sys import urllib2 import psycopg2 import psycopg2.extras import xlrd #/* ======================================================================= */#", "i = 0 arg_error = False while i < len(args): try: arg =", "'\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.materials_url", "# This catches three conditions: # 1. The last argument is a flag", "--db-* options are ignored. --db-host Hostname for the target database [default: localhost] --db-user", "except IndexError: i += 1 arg_error = True print(\"ERROR: An argument has invalid", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'cause', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_CAUSE', 'processing':", "eliminates repitition :param workbook: :type workbook: :param row: :type row: :param map_def: :type", "cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define process_field_map() function", "args: list :return: 0 on success and 1 on error :rtype: int \"\"\"", "if map_def['column'] not in column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source: %s", "that but must still supply the expected post-normalization format if unit.upper() not in", "method #/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */#", "complicated field map states that a specific function must do more of the", "column_names(sheet): validate_field_map_error = True print(\"ERROR: Can't find source: %s -> %s.%s\" % (file_to_process,", "*/# #/* Define print_version() function #/* ======================================================================= */# def print_version(): \"\"\" Print script", "it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return output", "= list(set(unique_report_ids)) # Grab a subsample if necessary if process_subsample is not None", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing': None },", "Define timestamp2datetime() function #/* ======================================================================= */# def timestamp2datetime(stamp, workbook_datemode, formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert", "processing function in order to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor, uid=uid,", "into which table in which schema. Each field map is applied against each", "= db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map definitions #/* ----------------------------------------------------------------------- */#", "a Postgres supported timestamp format. This method eliminates repitition :param workbook: :type workbook:", "...\") num_ids = len(unique_report_ids) uid_i = 0 # Loop through the primary keys", "into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# if map_def['processing'] is None: try: value = row[map_def['column']]", "{1} [--db-pass password] [--no-print-progress] [--print-queries] {1} [--no-execute-queries] [--overwrite] Options: --db-connection-string Explicitly define a", "#/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\" Some fields in the NRC spreadsheet do", "'public', 'sheet_name': 'CALLS', 'column': 'SEQNOS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'recieved_datetime',", "map sheet_seqnos_field The field in all sheets containing the reportnum uid The current", "TODO: Delete constraining line - needed to verify everything was wroking unique_report_ids =", "'args': { # Essentially kwargs 'Arg1': parameter, 'Arg2': ... } } }, {", "on each of the field map classes so we don't have to #", "I/O elif arg == '--no-download': i += 1 download_file = False elif arg", "'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } },", "Parse arguments map_def = kwargs['map_def'] print_queries = kwargs['print_queries'] execute_queries = kwargs['execute_queries'] extras_field_maps =", "print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name, map_def['db_schema'], map_def['db_table'], map_def['db_field'])) # Encountered", "= [str(uid)] else: # Get the row for this sheet try: row =", "cell in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function #/* ======================================================================= */#", "*/# def process_field_map(**kwargs): db_cursor = kwargs['db_cursor'] uid = kwargs['uid'] workbook = kwargs['workbook'] row", "if necessary if process_subsample is not None and process_subsample < len(unique_report_ids): # TODO:", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the", "column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'platform_letter', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "extracted as described in the field map sheet_seqnos_field The field in all sheets", "'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, }", "formatted database connection string :type cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode", "for exit code purposes :rtype: int \"\"\" print(__license__) return 1 #/* ======================================================================= */#", "table :param seqnos: reportnum :type seqnos: int|float :param field: :type field: :return: :rtype:", "Generate the output Current.xlsx name for permanent archival :param input_name: input file name", "} }, { # TODO: Implement 'db_table': '\"NrcParsedReport\"', 'db_field': 'affected_area', 'db_schema': 'public', 'sheet_name':", "Row 3 Values\" Example Output: [ { 'Column1': 'Row 1 Val', 'Column2': 'Another", "treated as primary keys and drive processing. Rather than process the input document", "} }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None,", "= True print(\"ERROR: An argument has invalid parameters\") #/* ----------------------------------------------------------------------- */# #/* Adjust", "'db_table': '\"NrcParsedReport\"', 'db_field': 'blockid', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function':", "+ int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower() in ('s', 'w'):", "# Execute query, but not if the report already exists query = \"\"\"%s", "Check each field definition in the set of mappings for map_def in field_map[db_map]:", "sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */#", "Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries Print queries immediately before execution", "parent process so this value is # returned at the very end if", "db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline Execution #/* ======================================================================= */# if", "in the 'RESPONSIBLE_COMPANY' column in the 'CALLS' sheet can be sent directly to", "arg == '--db-user': i += 2 db_user = args[i - 1] elif arg", "#/* Define time_stamp() static method #/* ----------------------------------------------------------------------- */# @staticmethod def time_stamp(**kwargs): \"\"\" Required", "and 1 on error :rtype: int \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define Field", "did not properly consume all parameters for an argument # 3. The arg", "def report_exists(**kwargs): \"\"\" Check to see if a report has already been submitted", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep #/* -----------------------------------------------------------------------", "= %s\"\"\" % (schema, table, field, reportnum)) return len(cursor.fetchall()) > 0 #/* =======================================================================", "print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing function handled ALL inserts", "name for permanent archival :param input_name: input file name (e.g. Current.xlsx) :type input_name:", "% schema_table cursor.execute(query) result = cursor.fetchall() return int(result[0][0]) #/* ======================================================================= */# #/* Define", "handled ALL inserts - tell parent process there's nothing left to do return", "kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO: This currently only reads", "#/* ----------------------------------------------------------------------- */# #/* Cleanup and final return #/* ----------------------------------------------------------------------- */# # Update", "(e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted name :rtype: str|unicode \"\"\" dt", "DB query = \"SELECT * FROM information_schema.columns WHERE table_schema = '%s' AND table_name", "{ts: db_row_count(db_cursor, ts) for ts in final_table_counts} #/* ----------------------------------------------------------------------- */# #/* Additional prep", "is used as a namespace to provide better organization and to prevent having", "the processing function in order to get a result else: value = map_def['processing']['function'](db_cursor=db_cursor,", "None }, { 'db_table': '\"BotTaskStatus\"', 'db_field': 'status', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "quotes cause problems on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except KeyError:", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "'db_field': 'recieved_datetime', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'DATE_TIME_RECEIVED', 'processing': { 'function': NrcScrapedReportFields.recieved_datetime }", "in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'], sheet_seqnos_field=sheet_seqnos_field,", "Val', 'Column2': 'Another Row 1 Val', 'Column3': 'Even More Row 1 Values' },", "keys set to schema.table db_cursor The cursor to be used for all queries", "dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row 1", "(ValueError, KeyError): output = kwargs['db_null_value'] return output #/* ----------------------------------------------------------------------- */# #/* Define latitude()", "in field_map[db_map]: # Attempt to get the sheet to test if map_def['sheet_name'] is", "+ ' ' * (padding - len(schema_table) + 4), count)) print(\"Final row counts:\")", "# Success - commit inserts and destroy DB connections # db_conn.commit() # connection", "'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"',", "#/* ======================================================================= */# #/* Define NrcScrapedReportField() class #/* ======================================================================= */# class NrcScrapedReportFields(object): \"\"\"", "= row[map_def['column']] except KeyError: # UID doesn't appear in the specified sheet -", "Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert", "NrcScrapedMaterialFields.ft_id } }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column':", "formatter='%Y-%m-%d %I:%M:%S'): \"\"\" Convert a float formatted date a Postgres supported timestamp :param", "# in the Software without restriction, including without limitation the rights # to", "'\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, {", "print(\"Caching sheets ...\") sheet_cache = {} raw_sheet_cache = {} for sname in workbook.sheet_names():", "currently only reads rows from the sheet specified in the field map and", "'w') as f: f.write(response.read()) return destination #/* ======================================================================= */# #/* Define name_current_file() function", "#/* ----------------------------------------------------------------------- */# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/*", "while i < len(args): try: arg = args[i] # Help arguments if arg", ":return: \"\"\" # TODO: Use 24 hour time workbook = kwargs['workbook'] row =", "}, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing':", "1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample] #/* ----------------------------------------------------------------------- */# #/* Process data", "#/* Define full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "sheets containing the reportnum uid The current SEQNOS/reportnum being processed workbook XLRD workbook", "--overwrite-download If the --file-to-process already exists and --no-download has not been specified, blindly", "} }, { # TODO: Implement - check notes about which column to", "next test fails try: value = float(value) except ValueError: value = '' #", "Single quotes cause problems on insert try: if e_map_def['db_field_width']: value = value[:e_map_def['db_field_width']] except", "'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'ft_id', 'db_schema': 'public',", "Success - commit inserts and destroy DB connections # db_conn.commit() # connection is", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return", "arg == '--subsample-min': i += 2 process_subsample_min = args[i - 1] # Positional", "'db_table': '\"NrcParsedReport\"', 'db_field': 'sheen_size_width', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_WIDTH', 'processing': { 'function':", "db_conn.commit() # connection is now set to autocommit db_cursor.close() db_conn.close() return 0 #/*", "'calltype', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } },", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Execute query, but not if the report already exists query", "a field containing \"1.23 METERS\" # This function takes care of that but", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "the same general logic. \"\"\" try: row = kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "} ] } } } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public',", "= 0 arg_error = False while i < len(args): try: arg = args[i]", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'CHRIS_CODE', 'processing':", "with additional processing #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Pass all necessary information to the", "%s\" % (overwrite, destination)) # Download response = urllib2.urlopen(url) with open(destination, 'w') as", "print(\"ERROR: Could not download from URL: %s\" % download_url) print(\" URLLIB Error: %s\"", "handled elsewhere so this is more of a safety net if value is", "the NRC spreadsheet do not map directly to a column in the database.", "sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet):", "}, { 'Column1': 'Row 2 Val', 'Column2': 'Another Row 2 Val', 'Column3': 'Even", "(the \"Software\"), to deal in the Software without restriction, including without limitation the", "single field map to process for map_def in field_map[db_map]: # Don't need to", "If no additional processing is required, simply grab the value from the sheet", "{ # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "- len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts and", "now set to autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline", "\"\"\"%s %s.%s (%s) VALUES (%s);\"\"\" % (db_write_mode, e_map_def['db_schema'], e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values))", "needed by the field definitions as dictionaries print(\"Caching sheets ...\") sheet_cache = {}", "#/* ======================================================================= */# #/* Define dms2dd() function #/* ======================================================================= */# def dms2dd(degrees, minutes,", "map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "the 'i' variable except IndexError: i += 1 arg_error = True print(\"ERROR: An", "'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes':", "# Get field maps for one table for db_map in field_map_order: query_fields =", "#/* ======================================================================= */# #/* Build information #/* ======================================================================= */# __version__ = '0.1-dev' __release__", "'MATERIAL_INVOLVED', 'column': 'UNIT_OF_MEASURE_REACH_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'chris_code', 'db_schema': 'public',", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "*/# #/* Define BotTaskStatusFields() class #/* ======================================================================= */# class BotTaskStatusFields(object): \"\"\" Some fields", "[] for s_name, s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids =", "'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } } }, { # TODO:", "4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts and destroy DB connections", "value = value[:e_map_def['db_field_width']] except KeyError: pass extra_query_values.append(\"'%s'\" % value) # String value else:", "Software without restriction, including without limitation the rights # to use, copy, modify,", "sname in workbook.sheet_names(): if sname not in sheet_cache: try: sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname]", "padding = max([len(i) for i in field_map.keys()]) indent = \" \" * 2", "incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def incident_datetime(**kwargs): \"\"\" See documentation for function", "Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/* ======================================================================= */#", "#/* ----------------------------------------------------------------------- */# @staticmethod def material_name(**kwargs): # Parse arguments map_def = kwargs['map_def'] print_queries", "'r') as workbook: # Establish a DB connection and turn on dict reading", "% download_url) print(\" URLLIB Error: %s\" % e) return 1 # Prep workbook", "--usage Arguments, parameters, flags, options, etc. --version Version and ownership information --license License", "= [i for i in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids =", "'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id }", "and table exist in the DB query = \"SELECT * FROM information_schema.columns WHERE", "autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline Execution #/* =======================================================================", "int :param seconds: coordinate seconds :type seconds: int :param quadrant: coordinate quadrant (N,", "the expected post-normalization format if unit.upper() not in multipliers: return db_null_value return unicode(multipliers[unit.upper()]", "function #/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting a", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None, 'processing': {", "the entire # value is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" %", "sheet in input file, 'column': Name of source column in sheet_name, 'processing': {", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime } }, {", ":rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/*", "--no-execute-queries Don't execute queries \"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/* =======================================================================", "printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts}", "'Even more Row 2 Values' } { 'Column1': 'Row 3 Val', 'Column2': 'Another", "from URL: %s\" % download_url) print(\" URLLIB Error: %s\" % e) return 1", "more of the heavy lifting. Field maps are grouped by table and center", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'materials_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "to be accidentally deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail =", "s_rows in sheet_cache.iteritems(): for reportnum in s_rows.keys(): unique_report_ids.append(reportnum) unique_report_ids = list(set(unique_report_ids)) # Grab", "len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for", "+ ' ' * (padding - len(schema_table) + 4), final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) #", "----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB: %s\" % db_connection_string) try: connection", "part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License", "line - needed to verify everything was wroking unique_report_ids = [i for i", "kwargs['uid'] workbook = kwargs['workbook'] row = kwargs['row'] db_null_value = kwargs['db_null_value'] map_def = kwargs['map_def']", "Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\" See documentation for", "the downloaded file is not going to be accidentally deleted if download_file and", "= datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/*", "or unit == '': return db_null_value # Found a sheen size and unit", "and column 'RESPONSIBLE_COMPANY' can be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map", "dictionary :rtype: dict \"\"\" output = [] columns = column_names(sheet) for r in", "def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method", "order to be excluded from the insert statement for that table. { 'db_table':", "% (db_write_mode, db_map, \", \".join(query_fields), \", \".join(query_values)) if print_queries: print(\"\") try: print(query) except", "for all queries db_null_value Value to use for NULL db_seqnos_field The reportnum field", "NULL db_seqnos_field The reportnum field in the database db_write_mode The first part of", "+= 1 print_progress = False elif arg == '--print-queries': i += 1 print_queries", "= sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in sheet_dict} except IndexError: #", "with keys set to schema.table db_cursor The cursor to be used for all", "the user to overwrite the default credentials and settings if db_connection_string is None:", "directory: %s\" % dirname(file_to_process)) # Handle subsample if process_subsample is not None: try:", "kwargs['row'] col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant']", "kwargs['sheet_cache'] # TODO: This currently only reads rows from the sheet specified in", "str) or isinstance(value, unicode): # Having single quotes in the string causes problems", "psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field", "Options: --db-connection-string Explicitly define a Postgres supported connection string. All other --db-* options", "} { 'Column1': 'Row 3 Val', 'Column2': 'Another Row 3 Val', 'Column3': 'Even", "of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License (MIT)", "unicode): value = value.replace(\"'\", '\"') # Single quotes cause problems on insert try:", "- nothing to do if value == '' or unit == '': return", "\"\"\" #/* ----------------------------------------------------------------------- */# #/* Define material_name() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "table. The structure for field maps is roughly as follows: All field maps", "print_progress: sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field maps", "cursor: psycopg2.cursor :param schema_table: schema.table :type schema_table: str|unicode :return: number of rows in", "sheet object :param sheet: XLRD sheet object :type sheet: xlrd.Sheet :param formatter: :type", "excluded from the insert statement for that table. { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude',", "'column': 'INCIDENT_CAUSE', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'location', 'db_schema': 'public', 'sheet_name':", "}, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing':", "name containing datetime down to the second. --file-to-process Specify where the input file", "Copyright (c) 2014 SkyTruth Permission is hereby granted, free of charge, to any", "else: cursor.execute(\"\"\"SELECT * FROM %s.%s WHERE %s = %s\"\"\" % (schema, table, field,", "db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) #/* ----------------------------------------------------------------------- */# #/* Validate field map definitions #/* ----------------------------------------------------------------------- */# validate_field_map_error", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\" See called function documentation", "'', u'', db_null_value): if isinstance(value, str) or isinstance(value, unicode): value = value.replace(\"'\", '\"')", "Commandline print-outs elif arg == '--no-print-progress': i += 1 print_progress = False elif", "= int(degrees) + int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower() in", "If the function itself handles all queries internally it can return '__NO_QUERY__' in", "+= 2 db_host = args[i - 1] elif arg == '--db-user': i +=", "download_file: print(\"Downloading: %s\" % download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "= kwargs['map_def'] db_null_value = kwargs['db_null_value'] value = row[map_def['column']] unit = row[map_def['processing']['args']['unit_field']] # If", "all options: This field map shows that no specific column contains the value", "called function documentation \"\"\" return NrcParsedReportFields._sheen_handler(**kwargs) #/* ----------------------------------------------------------------------- */# #/* Define affected_area() static", "#/* ======================================================================= */# #/* Define column_names() function #/* ======================================================================= */# def column_names(sheet, formatter=str):", "used for database connection [default: current user] --db-name Name of target database [default:", "None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail = True", "\"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static method #/* -----------------------------------------------------------------------", "- 1] # Commandline print-outs elif arg == '--no-print-progress': i += 1 print_progress", "is single quoted value = value.replace(\"'\", '\"') query_values.append(\"'%s'\" % value) else: query_values.append(\"%s\" %", "'--no-print-progress': i += 1 print_progress = False elif arg == '--print-queries': i +=", "db_null_value Value to use for NULL db_seqnos_field The reportnum field in the database", "'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema':", "row in sheet_dict} except IndexError: # Sheet was empty pass # Get a", "'\"NrcScrapedReport\"', 'db_field': 'incident_datetime', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'INCIDENT_DATE_TIME', 'processing': { 'function': NrcScrapedReportFields.incident_datetime", "of field maps for a single table to process # Get a field", "in sheet.row(0)] #/* ======================================================================= */# #/* Define sheet2dict() function #/* ======================================================================= */# def", "'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'material_name', 'db_schema':", "download the input file --overwrite-download If the --file-to-process already exists and --no-download has", "field: :return: :rtype: bool \"\"\" reportnum = kwargs['reportnum'] cursor = kwargs['db_cursor'] table =", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'full_report_url', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "IN THE SOFTWARE. ''' #/* ======================================================================= */# #/* Define print_usage() function #/* =======================================================================", "to download from :type url: str|unicode :param destination: target path and filename for", "{ 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': {", "'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcParsedReportFields.time_stamp, } }, { 'db_table':", "final value to be inserted into the target field described in the field", "sheet_dict = sheet2dict(workbook.sheet_by_name(sname)) raw_sheet_cache[sname] = sheet_dict sheet_cache[sname] = {row[sheet_seqnos_field]: row for row in", "Database connection elif arg == '--db-connection-string': i += 2 db_connection_string = args[i -", "#/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL value", "values row The current row being processed - structured just like a csv.DictReader", "used as a namespace to provide better organization and to prevent having to", "source: %s -> %s.%s\" % (file_to_process, map_def['sheet_name'], map_def['column'])) # Could not get the", "something like: 'get_NrcScrapedReport_material_name_field' \"\"\" #/* ----------------------------------------------------------------------- */# #/* Define status() static method #/*", "*/# #/* Value goes from input file straight into DB #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */#", "= kwargs['uid'] sheet_seqnos_field = kwargs['sheet_seqnos_field'] db_cursor = kwargs['db_cursor'] raw_sheet_cache = kwargs['raw_sheet_cache'] db_seqnos_field =", "+ int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output *= -1 return", "this hack with something better. # Perhpas have a report_exists method on each", "'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column':", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "and associated documentation files (the \"Software\"), to deal # in the Software without", "{ 'db_table': Name of target table, 'db_field': Name of target field, 'db_field_width': Maximum", "e_map_def['db_table'], ', '.join(extra_query_fields), ', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) #", "'\"NrcScrapedReport\"', 'db_field': 'medium_affected', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, {", "specified by the user. This set of ID's are treated as primary keys", "for final stat printing #/* ----------------------------------------------------------------------- */# initial_db_row_counts = {ts: db_row_count(db_cursor, ts) for", "None: #/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# #/* Value goes from input file straight into DB", "# # Copyright (c) 2014 SkyTruth # # Permission is hereby granted, free", "[default: Current_<CURRENT_DATETIME>.xlsx] --no-print-progress Don't print the progress indicator --print-queries Print queries immediately before", "try: arg = args[i] # Help arguments if arg in ('--help-info', '-help-info', '--helpinfo',", "as described in the field map sheet_seqnos_field The field in all sheets containing", "function #/* ======================================================================= */# def dms2dd(degrees, minutes, seconds, quadrant): \"\"\" Convert degrees, minutes,", "= row[map_def['column']] # ALL occurrences are sent to a different table - specified", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'SEQNOS', 'processing': None", "turn on dict reading db_conn = psycopg2.connect(db_connection_string) db_conn.autocommit = True db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)", "2014 SkyTruth Permission is hereby granted, free of charge, to any person obtaining", "a set of SEQNOS/reportnum's are gathered from one of the workbook's sheets. The", "*/# bail = False # Make sure arguments were properly parse if arg_error:", "primary keys and drive processing. Rather than process the input document sheet by", "of target schema, 'sheet_name': Name of source sheet in input file, 'column': Name", "----------------------------------------------------------------------- */# #/* Define incident_datetime() function #/* ----------------------------------------------------------------------- */# @staticmethod def calltype(**kwargs): \"\"\"", "*/# @staticmethod def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define main() function", "{ 'db_table': '\"NrcParsedReport\"', 'db_field': 'zip', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None", "indicator --print-queries Print queries immediately before execution Automatically turns off the progress indicator", "dict \"\"\" output = [] columns = column_names(sheet) for r in range(1, sheet.nrows):", "'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column':", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "def bot(**kwargs): return 'NrcExtractor' #/* ======================================================================= */# #/* Define main() function #/* =======================================================================", "datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* ======================================================================= */# #/* Define get_current_spreadsheet() function #/* =======================================================================", "exists: %s\" % (overwrite, destination)) # Download response = urllib2.urlopen(url) with open(destination, 'w')", "parse, transform, and insert Current.xlsx into the tables used by the Alerts system.", "#/* ======================================================================= */# def db_row_count(cursor, schema_table): \"\"\" :param cursor: Postgres formatted database connection", "\" \" * 2 print(\"Initial row counts:\") for schema_table, count in initial_db_row_counts.iteritems(): print(\"%s%s%s\"", "'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'MEDIUM_DESC', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "file --no-download Don't download the input file --overwrite-download If the --file-to-process already exists", "Val', 'Column3': 'Even More Row 1 Values' }, { 'Column1': 'Row 2 Val',", "*/# #/* Define sheen_size_width() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_width(**kwargs): \"\"\"", "{ 'db_table': \"NrcScrapedMaterial\", 'db_field': 'reportnum', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'SEQNOS', 'processing': None", "Attempt to get the sheet to test if map_def['sheet_name'] is not None and", "not results: validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" % (db_host, db_name,", "but must still supply the expected post-normalization format if unit.upper() not in multipliers:", "not used 'function': Callable object responsible for additional sub-processing 'args': { # Essentially", "'--db-connection-string': i += 2 db_connection_string = args[i - 1] elif arg == '--db-host':", "\"\"\".format(__docname__, \" \" * len(__docname__))) return 1 #/* ======================================================================= */# #/* Define print_license()", "----------------------------------------------------------------------- */# #/* Adjust options #/* ----------------------------------------------------------------------- */# # Database - must be", "Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1 Val\",\"Even More Row 1 Values\" \"Row", "db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value #/* ======================================================================= */# #/* Define NrcScrapedReportField()", "'col_quadrant': 'LONG_QUAD' } } }, { # TODO: Implement - check notes about", "timestamp field :rtype: str|unicode \"\"\" dt = datetime(*xlrd.xldate_as_tuple(stamp, workbook_datemode)) return dt.strftime(formatter) #/* =======================================================================", "'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.full_report_url } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "degrees :rtype: float \"\"\" illegal_vals = (None, '', u'') for iv in illegal_vals:", "final_db_row_counts[schema_table] - initial_db_row_counts[schema_table])) # Success - commit inserts and destroy DB connections #", "----------------------------------------------------------------------- */# #/* Define recieved_time() function #/* ----------------------------------------------------------------------- */# @staticmethod def recieved_datetime(**kwargs): \"\"\"", "# Found a matching row if row[sheet_seqnos_field] == uid: # The first instance", "\"\"\" illegal_vals = (None, '', u'') for iv in illegal_vals: if iv in", "Get a single field map to process for map_def in field_map[db_map]: # Don't", "db_cursor.fetchall() if not results: validate_field_map_error = True print(\"ERROR: Invalid DB target: %s.%s.%s.%s.%s\" %", "}, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'state', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_STATE', 'processing':", "function where the actual processing happens. Field maps using additional processing always receive", "3. The arg parser did not properly iterate the 'i' variable except IndexError:", "through the primary keys for uid in unique_report_ids: # Update user uid_i +=", "value = row[map_def['column']] if value == 'INC': value = 'INCIDENT' return value #/*", "'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} } },", "*/# def report_exists(**kwargs): \"\"\" Check to see if a report has already been", "input_name: input file name (e.g. Current.xlsx) :type input_name: str|unicode :return: output formatted name", "], } The order of operations for a given ID is as follows:", ":param quadrant: coordinate quadrant (N, E, S, W) :type quadrant: str|unicode :return: decimal", "1]) # Database connection elif arg == '--db-connection-string': i += 2 db_connection_string =", "[--download-url URL] {1} [--db-connection-string] [--db-host hostname] [--db-user username] {1} [--db-pass password] [--no-print-progress] [--print-queries]", "dt = datetime.now() dt = dt.strftime(\"_%Y-%m-%d_%I:%M:%S\") input_split = input_name.split('.') input_split[0] += dt return", "# TODO: Delete constraining line - needed to verify everything was wroking unique_report_ids", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ZIP', 'processing': None }, { # TODO: Implement", "This processing function handled ALL inserts - tell parent process there's nothing left", "sheet: XLRD sheet object :type sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return:", "row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet_cache[map_def['sheet_name']], all_field_maps=field_map, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field, sheet_cache=sheet_cache) #/*", "#/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */# # Handle NULL values - these should be handled elsewhere", "The current SEQNOS/reportnum being processed workbook XLRD workbook object The callable object specified", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/* Commandline Execution #/* ======================================================================= */#", "a NULL value \"\"\" return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _coord_formatter()", "intended to return a final value to be inserted into the target field", "str|unicode :param destination: target path and filename for downloaded file :type destination: str|unicode", "download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR: Could not download from URL: %s\" %", "# Grab a subsample if necessary if process_subsample is not None and process_subsample", "permission to the target directory if not os.access(dirname(file_to_process), os.W_OK): bail = True print(\"ERROR:", "e_map_def in extras_field_maps[e_db_map]: value = process_field_map(db_cursor=db_cursor, uid=uid, workbook=kwargs['workbook'], row=row, db_null_value=db_null_value, map_def=e_map_def, sheet=sheet_cache[e_map_def['sheet_name']], all_field_maps=kwargs['all_field_maps'],", "example below states that whatever value is in sheet 'CALLS' and column 'RESPONSIBLE_COMPANY'", "db_connection_string is None: db_connection_string = \"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user,", "column names :rtype: list \"\"\" return [formatter(cell.value) for cell in sheet.row(0)] #/* =======================================================================", "of the heavy lifting. Field maps are grouped by table and center around", "Define get_current_spreadsheet() function #/* ======================================================================= */# def download(url, destination, overwrite=False): \"\"\" Download a", "full_report_url() static method #/* ----------------------------------------------------------------------- */# @staticmethod def full_report_url(**kwargs): \"\"\" Default value \"\"\"", "*/# # Test connection print(\"Connecting to DB: %s\" % db_connection_string) try: connection =", "below) print_queries Specifies whether or not queries should be printed as they are", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_field_width': 32, 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY',", "processing #/* ----------------------------------------------------------------------- */# # Test connection print(\"Connecting to DB: %s\" % db_connection_string)", "connection string. All other --db-* options are ignored. --db-host Hostname for the target", "= max([len(i) for i in field_map.keys()]) indent = \" \" * 2 print(\"Initial", "= kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output =", "I/O download_url = 'http://nrc.uscg.mil/FOIAFiles/Current.xlsx' file_to_process = os.getcwd() + sep + name_current_file(basename(download_url)) overwrite_downloaded_file =", "Example field map with all options: This field map shows that no specific", "timestamp :param stamp: timestamp from XLRD reading a date encoded field :type stamp:", "*/# #/* Define NrcParsedReportFields() class #/* ======================================================================= */# class NrcParsedReportFields(object): \"\"\" Some fields", "*/# #/* Define ft_id() static method #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\"", "commit inserts and destroy DB connections # db_conn.commit() # connection is now set", "'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'AMOUNT_IN_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water_unit',", "number of rows in the specified schema.table :rtype: int \"\"\" query = \"\"\"SELECT", "namespace to provide better organization and to prevent having to name functions something", "'RESPONSIBLE_COMPANY', 'processing': None }, Example field map with all options: This field map", "exit code purposes :rtype: int \"\"\" print(\"\"\" Help flags: --help More detailed description", "#/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache all sheets needed by the", "elif arg == '--no-download': i += 1 download_file = False elif arg ==", "'sheet_name': 'CALLS', 'column': 'CALLTYPE', 'processing': { 'function': NrcScrapedReportFields.calltype } }, { 'db_table': '\"NrcScrapedReport\"',", "% download_url) print(\"Target: %s\" % file_to_process) try: download(download_url, file_to_process) except urllib2.URLError, e: print(\"ERROR:", "'--db-user': i += 2 db_user = args[i - 1] elif arg == '--db-name':", "to get the sheet to test if map_def['sheet_name'] is not None and map_def['column']", "NrcParsedReportFields.longitude, 'args': { 'col_degrees': 'LONG_DEG', 'col_minutes': 'LONG_MIN', 'col_seconds': 'LONG_SEC', 'col_quadrant': 'LONG_QUAD' } }", "since it contains the header output.append(dict((columns[c], sheet.cell_value(r, c)) for c in range(sheet.ncols))) return", "\"\"\" #/* ----------------------------------------------------------------------- */# #/* Define areaid() static method #/* ----------------------------------------------------------------------- */# @staticmethod", "db_null_value return unicode(multipliers[unit.upper()] * value) + ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define", ":type sheet: xlrd.Sheet :param formatter: :type formatter: type|function :return: list of column names", "#/* ----------------------------------------------------------------------- */# #/* Additional prep #/* ----------------------------------------------------------------------- */# # Cache all sheets", "AND task_id = %s\"\"\" % (schema, table, reportnum)) else: cursor.execute(\"\"\"SELECT * FROM %s.%s", "- needed to verify everything was wroking unique_report_ids = [i for i in", "if map_def['db_field'] == db_seqnos_field: query_fields = [db_seqnos_field] query_values = [str(uid)] else: # Get", "= kwargs['raw_sheet_cache'] db_seqnos_field = kwargs['db_seqnos_field'] db_null_value = kwargs['db_null_value'] sheet_cache = kwargs['sheet_cache'] # TODO:", "sys.stdout.write(\"\\r\\x1b[K\" + \" %s/%s\" % (uid_i, num_ids)) sys.stdout.flush() # Get field maps for", "the parameter # 2. The arg parser did not properly consume all parameters", "'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'description',", "= args[i] # Help arguments if arg in ('--help-info', '-help-info', '--helpinfo', '-help-info'): return", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define platform_letter() static method #/* ----------------------------------------------------------------------- */#", "Rather than process the input document sheet by sheet and row by row,", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "download_file and not overwrite_downloaded_file and isfile(file_to_process): bail = True print(\"ERROR: Overwrite=%s and download", "can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any additional processing. Note the quotes", "each structured as a dictionary Example Input: \"Column1\",\"Column2\",\"Column3\" \"Row 1 Val\",\"Another Row 1", "so the next test fails try: value = float(value) except ValueError: value =", "'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } }, { 'db_table': '\"NrcParsedReport\"', 'db_field':", "of ID's are treated as primary keys and drive processing. Rather than process", "used 'function': Callable object responsible for additional sub-processing 'args': { # Essentially kwargs", "return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define st_id() static method #/* -----------------------------------------------------------------------", "going to be accidentally deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process): bail", "Found a sheen size and unit - perform conversion else: multipliers = {", "values if isinstance(value, str) or isinstance(value, unicode): # Having single quotes in the", "# Database is expecting to handle the normalization by reading from a field", "----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to insert a NULL value \"\"\"", "\"\"\" Print a list of help related flags :return: 1 for exit code", "do return initial_value_to_be_returned #/* ----------------------------------------------------------------------- */# #/* Define full_report_url() static method #/* -----------------------------------------------------------------------", "be sent to public.\"NrcScrapedReport\".suspected_responsible_company The more complicated field map states that a specific", "} }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'longitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': None,", "'db_table': '\"NrcScrapedReport\"', 'db_field': 'suspected_responsible_company', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': 'RESPONSIBLE_COMPANY', 'processing': None },", "}, { # TODO: Not populated 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amount', 'db_schema': 'public', 'sheet_name':", "row counts:\") final_db_row_counts = {ts: db_row_count(db_cursor, ts) for ts in final_table_counts} for schema_table,", "1 Values\" \"Row 2 Val\",\"Another Row 2 Val\",\"Even More Row 2 Values\" \"Row", "#/* Define NrcScrapedMaterialFields() class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in", "required for public.\"NrcParsedReport\".longitude Instead, some information must be passed to the NrcParsedReportFields.longitude() function", "kwargs['db_null_value'] map_def = kwargs['map_def'] sheet = kwargs['sheet'] all_field_maps = kwargs['all_field_maps'] sheet_seqnos_field = kwargs['sheet_seqnos_field']", "XLRD sheet object :param sheet: XLRD sheet object :type sheet: xlrd.Sheet :param formatter:", "schema and table exist in the DB query = \"SELECT * FROM information_schema.columns", "not connect to database: %s\" % db_connection_string) print(\" Postgres Error: %s\" % e)", "blockid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/* -----------------------------------------------------------------------", "\"NrcScrapedMaterial\", 'db_field': 'reached_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, {", "__future__ import unicode_literals from datetime import datetime import getpass import os from os.path", "field maps for one table for db_map in field_map_order: query_fields = [] query_values", "require an additional processing step that is highly specific and cannot be re-used.", "----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters require \"\"\" row = kwargs['row']", "a specific target for the download, this flag is not needed due the", "1 for exit code purposes :rtype: int \"\"\" print(__license__) return 1 #/* =======================================================================", "None, 'processing': { 'function': NrcParsedReportFields.areaid } }, { # TODO: Implement - check", "0.0833333, 'KILOMETERS': 3280.84, 'METER': 3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280,", "i in unique_report_ids if i > 1074683] unique_report_ids.sort() unique_report_ids = unique_report_ids[process_subsample_min:process_subsample_min + process_subsample]", "\"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/* Define time_stamp() static", "table in which schema. Each field map is applied against each ID which", "code purposes :rtype: int \"\"\" print(\"\"\" Usage: {0} [--help-info] [options] [--no-download] [--download-url URL]", "is properly quoted if value not in (None, '', u'', db_null_value): if isinstance(value,", "is now set to autocommit db_cursor.close() db_conn.close() return 0 #/* ======================================================================= */# #/*", "= '%s';\" \\ % (map_def['db_schema'], map_def['db_table'].replace('\"', ''), map_def['db_field']) db_cursor.execute(query) results = db_cursor.fetchall() if", "replace this hack with something better. # Perhpas have a report_exists method on", "'INCIDENT_COMMONS', 'column': None, 'processing': { 'function': NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN',", "'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'time_stamp', 'db_schema': 'public',", "Grab a subsample if necessary if process_subsample is not None and process_subsample <", "is not None: try: process_subsample = int(process_subsample) process_subsample_min = int(process_subsample_min) except ValueError: bail", "uid: # The first instance goes into the table specified in the field", "def areaid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/*", "Define status() static method #/* ----------------------------------------------------------------------- */# @staticmethod def status(**kwargs): return 'DONE' #/*", "def blockid(**kwargs): # TODO: Implement - currently returning NULL return kwargs.get('db_null_value', None) #/*", "to process the reportnum information since it was added to the initial query", "{} raw_sheet_cache = {} for sname in workbook.sheet_names(): if sname not in sheet_cache:", "- initial_db_row_counts[schema_table])) # Success - commit inserts and destroy DB connections # db_conn.commit()", "True print(\"ERROR: Need write permission for download directory: %s\" % dirname(file_to_process)) # Handle", "{ 'db_table': '\"NrcScrapedReport\"', 'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None", "'function': Callable object responsible for additional sub-processing 'args': { # Essentially kwargs 'Arg1':", "process_subsample_min = int(process_subsample_min) except ValueError: bail = True print(\"ERROR: Invalid subsample or subsample", "('--version', '-version'): return print_version() elif arg in ('--license', '-usage'): return print_license() # Spreadsheet", "not None and map_def['column'] is not None: try: sheet = workbook.sheet_by_name(map_def['sheet_name']) if map_def['column']", "'ft_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function': NrcScrapedReportFields.ft_id } }", "kwargs 'Arg1': parameter, 'Arg2': ... } } }, { 'db_table': Name of target", "NrcParsedReportFields.latitude, 'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } }", "Print script version information :return: 1 for exit code purposes :rtype: int \"\"\"", "and insert Current.xlsx into the tables used by the Alerts system. http://nrc.uscg.mil/FOIAFiles/Current.xlsx Before", "% iv) if quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError(\"ERROR: Invalid", "The current row being processed - structured just like a csv.DictReader row sheet", "bail = True print(\"ERROR: Need write permission for download directory: %s\" % dirname(file_to_process))", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod", "destination #/* ======================================================================= */# #/* Define name_current_file() function #/* ======================================================================= */# def name_current_file(input_name):", "'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public', 'sheet_name': 'MATERIAL_INVOLVED',", "======================================================================= */# #/* Commandline Execution #/* ======================================================================= */# if __name__ == '__main__': sys.exit(main(sys.argv[1:]))", "col_deg = kwargs['map_def']['processing']['args']['col_degrees'] col_min = kwargs['map_def']['processing']['args']['col_minutes'] col_sec = kwargs['map_def']['processing']['args']['col_seconds'] col_quad = kwargs['map_def']['processing']['args']['col_quadrant'] output", "= input_name.split('.') input_split[0] += dt return '.'.join(input_split) #/* ======================================================================= */# #/* Define db_row_count()", "None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'county', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_COUNTY',", "which to download the input file --no-download Don't download the input file --overwrite-download", "write permission for download directory: %s\" % dirname(file_to_process)) # Handle subsample if process_subsample", "Help flags: --help More detailed description of this utility --usage Arguments, parameters, flags,", "*/# i = 0 arg_error = False while i < len(args): try: arg", "'args': { 'col_degrees': 'LAT_DEG', 'col_minutes': 'LAT_MIN', 'col_seconds': 'LAT_SEC', 'col_quadrant': 'LAT_QUAD' } } },", "Define _sheen_handler() static method #/* ----------------------------------------------------------------------- */# @staticmethod def _sheen_handler(**kwargs): \"\"\" Several converters", "notes about which column to use 'db_table': '\"NrcParsedReport\"', 'db_field': 'areaid', 'db_schema': 'public', 'sheet_name':", "class #/* ======================================================================= */# class NrcScrapedMaterialFields(object): \"\"\" Some fields in the NRC spreadsheet", "'skytruth' db_user = getpass.getuser() db_pass = '' db_write_mode = 'INSERT INTO' db_seqnos_field =", "24 hour time workbook = kwargs['workbook'] row = kwargs['row'] map_def = kwargs['map_def'] return", "extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) # Do something with the query", ":return: 1 for exit code purposes :rtype: int \"\"\" print(__license__) return 1 #/*", "not going to be accidentally deleted if download_file and not overwrite_downloaded_file and isfile(file_to_process):", "arg == '--overwrite-download': i += 1 overwrite_downloaded_file = True elif arg == '--subsample':", "\"\"\" from __future__ import division from __future__ import print_function from __future__ import unicode_literals", "for map_def in field_map[db_map]: # Don't need to process the reportnum information since", "order of operations for a given ID is as follows: 1. Get an", "unique_report_ids = list(set(unique_report_ids)) # Grab a subsample if necessary if process_subsample is not", "value) # String value else: extra_query_values.append(\"%s\" % value) # int|float value extra_query_fields.append(e_map_def['db_field']) #", "= kwargs['map_def'] row = kwargs['row'] value = row[map_def['column']] if value == 'INC': value", "to a different table - specified in the field map arguments for e_db_map", "#/* ----------------------------------------------------------------------- */# @staticmethod def _datetime_caller(**kwargs): \"\"\" Several methods require converting a timestamp", "Get a field map to process print(\"Processing workbook ...\") num_ids = len(unique_report_ids) uid_i", "output *= -1 return output #/* ======================================================================= */# #/* Define column_names() function #/*", "static method #/* ----------------------------------------------------------------------- */# @staticmethod def _coord_formatter(**kwargs): \"\"\" The latitude() and longitude()", "{ 'table_name': [ { 'db_table': Name of target table, 'db_field': Name of target", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "\"host='%s' dbname='%s' user='%s' password='%s'\" % (db_host, db_name, db_user, db_pass) #/* ----------------------------------------------------------------------- */# #/*", "are sent to a different table - specified in the field map arguments", "print_help(): \"\"\" Detailed help information :return: 1 for exit code purposes :rtype: int", "'SEQNOS', 'processing': None }, { 'db_table': '\"NrcParsedReport\"', 'db_field': 'latitude', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS',", "Validate parameters #/* ----------------------------------------------------------------------- */# bail = False # Make sure arguments were", "column in the 'CALLS' sheet can be sent directly to public.\"NrcScrapedReport\".suspected_responsible_company without any", "field :type stamp: float :param workbook_datemode: from xlrd.Workbook.datemode :type workbook_datemode: int :return: date", "*/# @staticmethod def affected_area(**kwargs): return kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define time_stamp()", "overwritten :type overwrite: bool :return: path to downloaded file :rtype: str|unicode \"\"\" #", "fails try: value = float(value) except ValueError: value = '' # No sheen", "3.28084, 'METERS': 3.28084, 'MI': 5280, 'MIL': 5280, 'MILES': 5280, 'NI': 5280, # Assumed", "for map_def in field_map[db_map]: # Attempt to get the sheet to test if", "kwargs.get('db_null_value', None) #/* ----------------------------------------------------------------------- */# #/* Define _datetime_caller() function #/* ----------------------------------------------------------------------- */# @staticmethod", "not needed due the default file name containing datetime down to the second.", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "in the database. These fields require an additional processing step that is highly", "with a list of rows instead of a dictionary containing reportnums as keys", "sheet by sheet and row by row, a set of field map definitions", "Define sheet2dict() function #/* ======================================================================= */# def sheet2dict(sheet): \"\"\" Convert an XLRD sheet", "Optional - should be set to None if not used 'function': Callable object", "the table specified in the field map # This query must be handled", "Define sheen_size_length() static method #/* ----------------------------------------------------------------------- */# @staticmethod def sheen_size_length(**kwargs): \"\"\" See called", "', '.join(extra_query_values)) if print_queries: print(\"\") print(query) if execute_queries: db_cursor.execute(query) # This processing function", "actual processing happens. Field maps using additional processing always receive the following kwargs:", "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", "incident_datetime(**kwargs): \"\"\" See documentation for function called in the return statement \"\"\" return", "\"\"\" % (__docname__, __version__, __release__)) return 1 #/* ======================================================================= */# #/* Define dms2dd()", "'db_field': 'nearestcity', 'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_NEAREST_CITY', 'processing': None }, { 'db_table':", "class BotTaskStatusFields(object): \"\"\" Some fields in the NRC spreadsheet do not map directly", "' ' * (padding - len(schema_table) + 4), count)) print(\"Final row counts:\") final_db_row_counts", "#/* Download the spreadsheet #/* ----------------------------------------------------------------------- */# if download_file: print(\"Downloading: %s\" % download_url)", "row=row, db_null_value=db_null_value, map_def=map_def, sheet=sheet, all_field_maps=all_field_maps, sheet_seqnos_field=sheet_seqnos_field, db_write_mode=db_write_mode, print_queries=print_queries, execute_queries=execute_queries, raw_sheet_cache=raw_sheet_cache, db_seqnos_field=db_seqnos_field) return value", "\"\"\" return 'http://nrc.uscg.mil/' #/* ----------------------------------------------------------------------- */# #/* Define materials_url() static method #/* -----------------------------------------------------------------------", "formatted date a Postgres supported timestamp :param stamp: timestamp from XLRD reading a", "*/# def print_license(): \"\"\" Print out license information :return: 1 for exit code", "the ordered column names from an XLRD sheet object :param sheet: XLRD sheet", "'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'st_id', 'db_schema': 'public', 'sheet_name': 'CALLS', 'column': None, 'processing': { 'function':", "'db_field': 'sheen_size_length', 'db_schema': 'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args':", "#/* Define ft_id() function #/* ----------------------------------------------------------------------- */# @staticmethod def ft_id(**kwargs): \"\"\" Required to", "'public', 'sheet_name': 'INCIDENT_DETAILS', 'column': 'SHEEN_SIZE_LENGTH', 'processing': { 'function': NrcParsedReportFields.sheen_size_length, 'args': {'unit_field': 'SHEEN_SIZE_LENGTH_UNITS'} }", "@staticmethod def materials_url(**kwargs): \"\"\" Default value \"\"\" return NrcScrapedReportFields.full_report_url() #/* ----------------------------------------------------------------------- */# #/*", "required, simply grab the value from the sheet and add to the query", "get the sheet to test if map_def['sheet_name'] is not None and map_def['column'] is", "the primary keys for uid in unique_report_ids: # Update user uid_i += 1", "hereby granted, free of charge, to any person obtaining a copy # of", "int: %s\" % process_subsample) # Exit if any problems were encountered if bail:", "+ ' FEET' #/* ----------------------------------------------------------------------- */# #/* Define sheen_size_length() static method #/* -----------------------------------------------------------------------", "Define print_help_info() function #/* ======================================================================= */# def print_help_info(): \"\"\" Print a list of", "*/# # Loops: # Get a report number to process # Get a", "processing functions. A class is used as a namespace to provide better organization", "'db_schema': 'public', 'sheet_name': 'INCIDENT_COMMONS', 'column': 'LOCATION_ADDRESS', 'processing': None }, { 'db_table': '\"NrcScrapedReport\"', 'db_field':", "kwargs 'Arg1': parameter, 'Arg2': ... } } } ], } The order of", "{ 'function': NrcScrapedReportFields.time_stamp } }, { 'db_table': '\"NrcScrapedReport\"', 'db_field': 'ft_id', 'db_schema': 'public', 'sheet_name':", "kwargs['table'] field = kwargs.get('field', 'reportnum') schema = kwargs['schema'] # TODO: replace this hack", "'MATERIAL_INVOLVED', 'column': 'IF_REACHED_WATER', 'processing': None }, { 'db_table': '\"NrcScrapedMaterial\"', 'db_field': 'amt_in_water', 'db_schema': 'public'," ]
[ "s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure following settings aws_profile = None", "manually configure following settings aws_profile = None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\"", "= None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses =", "-*- coding: utf-8 -*- \"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\"", "# -*- coding: utf-8 -*- \"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename}", "aws_profile = None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses", "<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" S3 object for testing naming convention::", "convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure following settings aws_profile =", "for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure following", "--- manually configure following settings aws_profile = None aws_region = \"us-east-1\" bucket =", "configure following settings aws_profile = None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix", "following settings aws_profile = None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix =", "utf-8 -*- \"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3", "# --- manually configure following settings aws_profile = None aws_region = \"us-east-1\" bucket", "import boto3 # --- manually configure following settings aws_profile = None aws_region =", "-*- \"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 #", "naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure following settings aws_profile", "coding: utf-8 -*- \"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import", "\"\"\" S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # ---", "\"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses = boto3.session.Session(profile_name=aws_profile, region_name=aws_region) s3_client =", "aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses = boto3.session.Session(profile_name=aws_profile, region_name=aws_region)", "settings aws_profile = None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\"", "bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses = boto3.session.Session(profile_name=aws_profile, region_name=aws_region) s3_client = boto_ses.client(\"s3\")", "= \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses = boto3.session.Session(profile_name=aws_profile, region_name=aws_region) s3_client", "boto3 # --- manually configure following settings aws_profile = None aws_region = \"us-east-1\"", "testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure following settings", "\"\"\" import boto3 # --- manually configure following settings aws_profile = None aws_region", "S3 object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually", "None aws_region = \"us-east-1\" bucket = \"aws-data-lab-sanhe-aws-etl-solutions\" prefix = \"s3splitmerge/tests\" boto_ses = boto3.session.Session(profile_name=aws_profile,", "object for testing naming convention:: s3://{bucket}/{prefix}/{module}/{function/method_name}/{filename} \"\"\" import boto3 # --- manually configure" ]
[ "banner_card = Text() banner_page = Text() github = Text() donate = Text() privacy_policy", "(UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable", "= Integer(choices = enums.BotState, default = 1) description = Text() long_description_type = Integer(default", "Integer() vanity_url = Text(primary_key = True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch", "js_allowed = Boolean(default = False, help_text = \"Is the user allowed to use", "= Integer() vanity_url = Text(primary_key = True) redirect = BigInt() class User(Table, tablename=\"users\"):", "has\") review_text = Text() review_upvotes = Array(base_column = BigInt(), default = []) review_downvotes", "= \"Is the user allowed to use javascript\") api_token = Text() class Bot(Table,", "BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod def get_readable(cls): return", "BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable", "= 1) description = Text() long_description_type = Integer(default = 0, choices = enums.LongDescType)", "Text() invite_amount = Integer(default = 0) features = Array(base_column = Text(), default =", "= Text(default = \"\") user_css = Text(default = \"\") state = Integer(default =", "ForeignKey(references=Bot) tag = Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews", "modules.models import enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key =", "Badges. The ones currently on profiles are special and manually handled without using", "= False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your own through", "= Text() nsfw = Boolean(default = False) api_token = Text() js_allowed = Boolean(default", "0, choices = enums.UserState) coins = Integer(default = 0) js_allowed = Boolean(default =", "Text() banner_card = Text() banner_page = Text() github = Text() donate = Text()", "= Text(default = \"\") prefix = Varchar(length = 13) di_text = Text(help_text =", "= BigInt(default = 0) shard_count = BigInt(default = 0) shards = Array(base_column =", "this column.\") username = Text() profile_css = Text(default = \"\") user_css = Text(default", "enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key = True) redirect", "from piccolo.columns.column_types import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz,", "to use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier", "= Text() css = Text(default = \"\") prefix = Varchar(length = 13) di_text", "BigInt(default = 0) shards = Array(base_column = Integer()) user_count = BigInt(default = 0)", "username = Text() profile_css = Text(default = \"\") user_css = Text(default = \"\")", "BigInt(default = 0) shard_count = BigInt(default = 0) shards = Array(base_column = Integer())", "from piccolo.table import Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type =", "help_text = \"Custom User Badges. The ones currently on profiles are special and", "piccolo.table import Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type = Integer()", "0) guild_count = BigInt(default = 0) shard_count = BigInt(default = 0) shards =", "use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier =", "= Array(base_column = Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot)", "\"\") prefix = Varchar(length = 13) di_text = Text(help_text = \"Discord Integration Text\")", "ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table import", "Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod def", "Text\") website = Text() discord = Text() banner_card = Text() banner_page = Text()", "be an enigma\") badges = Array(base_column = Text(), help_text = \"Custom User Badges.", "= BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod def get_readable(cls):", "last voted\") description = Text(default = \"This user prefers to be an enigma\")", "using this column.\") username = Text() profile_css = Text(default = \"\") user_css =", "Text() donate = Text() privacy_policy = Text() nsfw = Boolean(default = False) api_token", "\"\"\"Never ever make reviews on your own through this panel\"\"\" id = UUID()", "Text(default = \"This user prefers to be an enigma\") badges = Array(base_column =", "= Integer()) user_count = BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at", "= BigInt(default = 0) shards = Array(base_column = Integer()) user_count = BigInt(default =", "import Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url", "= Text(help_text = \"Discord Integration Text\") website = Text() discord = Text() banner_card", "nsfw = Boolean(default = False) api_token = Text() js_allowed = Boolean(default = True)", "= Text() banner_page = Text() github = Text() donate = Text() privacy_policy =", "Text(), help_text = \"Custom User Badges. The ones currently on profiles are special", "vanity_url = Text(primary_key = True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch =", "to be an enigma\") badges = Array(base_column = Text(), help_text = \"Custom User", "= False, help_text = \"Is the user allowed to use javascript\") api_token =", "= \"\") state = Integer(default = 0, choices = enums.UserState) coins = Integer(default", "star_rating = Float(help_text = \"Amount of stars a bot has\") review_text = Text()", "badges = Array(base_column = Text(), help_text = \"Custom User Badges. The ones currently", "Integer(default = 0, choices = enums.UserState) coins = Integer(default = 0) js_allowed =", "Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType)", "from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key", "= \"Amount of stars a bot has\") review_text = Text() review_upvotes = Array(base_column", "= Text() js_allowed = Boolean(default = True) invite = Text() invite_amount = Integer(default", "= Boolean(default = True) invite = Text() invite_amount = Integer(default = 0) features", "redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user", "= BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default =", "= enums.BotState, default = 1) description = Text() long_description_type = Integer(default = 0,", "through this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id", "= 0, choices = enums.LongDescType) long_description = Text() votes = BigInt(default = 0)", "Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply =", "Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your own", "False, help_text = \"Is the user allowed to use javascript\") api_token = Text()", "shard_count = BigInt(default = 0) shards = Array(base_column = Integer()) user_count = BigInt(default", "= Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply", "\"Is the user allowed to use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"):", "user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars a bot has\")", "Boolean(default = False, help_text = \"Is the user allowed to use javascript\") api_token", "Integer(default = 0, choices = enums.LongDescType) long_description = Text() votes = BigInt(default =", "default=[]) flagged = Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(),", "from piccolo.columns.readable import Readable from piccolo.table import Table from modules.models import enums class", "reviews on your own through this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType)", "= []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null = False)", "Text() bot_library = Text() css = Text(default = \"\") prefix = Varchar(length =", "Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook = Text() bot_library =", "piccolo.columns.column_types import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar)", "= Text() verifier = BigInt() state = Integer(choices = enums.BotState, default = 1)", "api_token = Text() js_allowed = Boolean(default = True) invite = Text() invite_amount =", "= Text() bot_library = Text() css = Text(default = \"\") prefix = Varchar(length", "Text(default = \"\") user_css = Text(default = \"\") state = Integer(default = 0,", "= Integer(default = 0, choices = enums.LongDescType) long_description = Text() votes = BigInt(default", "target_id = BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars", "default = 1) description = Text() long_description_type = Integer(default = 0, choices =", "column.\") username = Text() profile_css = Text(default = \"\") user_css = Text(default =", "verifier = BigInt() state = Integer(choices = enums.BotState, default = 1) description =", "0) shard_count = BigInt(default = 0) shards = Array(base_column = Integer()) user_count =", "type = Integer() vanity_url = Text(primary_key = True) redirect = BigInt() class User(Table,", "Array(base_column = BigInt(), default = []) review_downvotes = Array(base_column = BigInt(), default=[]) flagged", "False) api_token = Text() js_allowed = Boolean(default = True) invite = Text() invite_amount", "0) shards = Array(base_column = Integer()) user_count = BigInt(default = 0) last_stats_post =", "= Integer(default = 0) js_allowed = Boolean(default = False, help_text = \"Is the", "review_upvotes = Array(base_column = BigInt(), default = []) review_downvotes = Array(base_column = BigInt(),", "discord = Text() banner_card = Text() banner_page = Text() github = Text() donate", "Boolean(default = True) invite = Text() invite_amount = Integer(default = 0) features =", "UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text", "shards = Array(base_column = Integer()) user_count = BigInt(default = 0) last_stats_post = Timestamptz(default", "= Text(), help_text = \"Custom User Badges. The ones currently on profiles are", "\"Discord Integration Text\") website = Text() discord = Text() banner_card = Text() banner_page", "Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table import Table", "= BigInt(), default = []) review_downvotes = Array(base_column = BigInt(), default=[]) flagged =", "Array(base_column = Text(), help_text = \"Custom User Badges. The ones currently on profiles", "last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices", "= Integer(choices = enums.WebhookType) webhook = Text() bot_library = Text() css = Text(default", "Text() nsfw = Boolean(default = False) api_token = Text() js_allowed = Boolean(default =", "= []) review_downvotes = Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch =", "Text() profile_css = Text(default = \"\") user_css = Text(default = \"\") state =", "BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars a bot", "= \"This user prefers to be an enigma\") badges = Array(base_column = Text(),", "prefers to be an enigma\") badges = Array(base_column = Text(), help_text = \"Custom", "= Integer(default = 0) features = Array(base_column = Text(), default = []) class", "= BigInt(default = 0) guild_count = BigInt(default = 0) shard_count = BigInt(default =", "without using this column.\") username = Text() profile_css = Text(default = \"\") user_css", "state = Integer(default = 0, choices = enums.UserState) coins = Integer(default = 0)", "css = Text(default = \"\") prefix = Varchar(length = 13) di_text = Text(help_text", "default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod def get_readable(cls): return Readable(template=\"%s\",", "= Text(default = \"This user prefers to be an enigma\") badges = Array(base_column", "= BigInt() state = Integer(choices = enums.BotState, default = 1) description = Text()", "import enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key = True)", "= 0) guild_count = BigInt(default = 0) shard_count = BigInt(default = 0) shards", "= 0) features = Array(base_column = Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"):", "tablename=\"bots\"): username_cached = Text() verifier = BigInt() state = Integer(choices = enums.BotState, default", "long_description_type = Integer(default = 0, choices = enums.LongDescType) long_description = Text() votes =", "= Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices =", "prefix = Varchar(length = 13) di_text = Text(help_text = \"Discord Integration Text\") website", "Text(help_text = \"Discord Integration Text\") website = Text() discord = Text() banner_card =", "= datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook", "Text() votes = BigInt(default = 0) guild_count = BigInt(default = 0) shard_count =", "= Text(default = \"\") state = Integer(default = 0, choices = enums.UserState) coins", "user_count = BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default", "class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key = True) redirect =", "vote_epoch = Timestamptz(help_text = \"When the user has last voted\") description = Text(default", "Varchar(length = 13) di_text = Text(help_text = \"Discord Integration Text\") website = Text()", "= 0) shards = Array(base_column = Integer()) user_count = BigInt(default = 0) last_stats_post", "state = Integer(choices = enums.BotState, default = 1) description = Text() long_description_type =", "username_cached = Text() verifier = BigInt() state = Integer(choices = enums.BotState, default =", "Text() review_upvotes = Array(base_column = BigInt(), default = []) review_downvotes = Array(base_column =", "id = UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating", "Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your own through this panel\"\"\" id", "= Text() votes = BigInt(default = 0) guild_count = BigInt(default = 0) shard_count", "invite = Text() invite_amount = Integer(default = 0) features = Array(base_column = Text(),", "Array(base_column = Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag", "BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies =", "= Array(base_column = Integer()) user_count = BigInt(default = 0) last_stats_post = Timestamptz(default =", "= Text() github = Text() donate = Text() privacy_policy = Text() nsfw =", "review_downvotes = Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column =", "user_css = Text(default = \"\") state = Integer(default = 0, choices = enums.UserState)", "= enums.LongDescType) long_description = Text() votes = BigInt(default = 0) guild_count = BigInt(default", "= \"When the user has last voted\") description = Text(default = \"This user", "github = Text() donate = Text() privacy_policy = Text() nsfw = Boolean(default =", "coins = Integer(default = 0) js_allowed = Boolean(default = False, help_text = \"Is", "= Text() privacy_policy = Text() nsfw = Boolean(default = False) api_token = Text()", "class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null = False) class Review(Table,", "default = []) review_downvotes = Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch", "on your own through this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id", "replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod def get_readable(cls): return Readable(template=\"%s\", columns=[cls.name])", "special and manually handled without using this column.\") username = Text() profile_css =", "0) js_allowed = Boolean(default = False, help_text = \"Is the user allowed to", "= Varchar(length = 13) di_text = Text(help_text = \"Discord Integration Text\") website =", "Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import", "= Integer(default = 0, choices = enums.UserState) coins = Integer(default = 0) js_allowed", "api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt() state", "= enums.WebhookType) webhook = Text() bot_library = Text() css = Text(default = \"\")", "Integer(default = 0) features = Array(base_column = Text(), default = []) class BotTag(Table,", "Text(default = \"\") prefix = Varchar(length = 13) di_text = Text(help_text = \"Discord", "\"\") user_css = Text(default = \"\") state = Integer(default = 0, choices =", "currently on profiles are special and manually handled without using this column.\") username", "= BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user has", "True) invite = Text() invite_amount = Integer(default = 0) features = Array(base_column =", "= ForeignKey(references=Bot) tag = Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make", "a bot has\") review_text = Text() review_upvotes = Array(base_column = BigInt(), default =", "\"\") state = Integer(default = 0, choices = enums.UserState) coins = Integer(default =", "help_text = \"Is the user allowed to use javascript\") api_token = Text() class", "enums.WebhookType) webhook = Text() bot_library = Text() css = Text(default = \"\") prefix", "and manually handled without using this column.\") username = Text() profile_css = Text(default", "allowed to use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached = Text()", "bot_id = ForeignKey(references=Bot) tag = Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever", "tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user has last voted\") description =", "1) description = Text() long_description_type = Integer(default = 0, choices = enums.LongDescType) long_description", "long_description = Text() votes = BigInt(default = 0) guild_count = BigInt(default = 0)", "Text(primary_key = True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text =", "= UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating =", "= \"Custom User Badges. The ones currently on profiles are special and manually", "\"When the user has last voted\") description = Text(default = \"This user prefers", "= Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column = BigInt(),", "= enums.UserState) coins = Integer(default = 0) js_allowed = Boolean(default = False, help_text", "= BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies", "enums.UserState) coins = Integer(default = 0) js_allowed = Boolean(default = False, help_text =", "Integration Text\") website = Text() discord = Text() banner_card = Text() banner_page =", "ever make reviews on your own through this panel\"\"\" id = UUID() target_type", "tag = Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on", "= Text() discord = Text() banner_card = Text() banner_page = Text() github =", "\"This user prefers to be an enigma\") badges = Array(base_column = Text(), help_text", "= Boolean(default = False, help_text = \"Is the user allowed to use javascript\")", "= 13) di_text = Text(help_text = \"Discord Integration Text\") website = Text() discord", "ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars a bot has\") review_text =", "choices = enums.UserState) coins = Integer(default = 0) js_allowed = Boolean(default = False,", "datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook =", "Readable from piccolo.table import Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type", "13) di_text = Text(help_text = \"Discord Integration Text\") website = Text() discord =", "<reponame>Fates-List/BotList<filename>modules/infra/admin_piccolo/tables.py import datetime from piccolo.columns.column_types import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer,", "= Text() banner_card = Text() banner_page = Text() github = Text() donate =", "make reviews on your own through this panel\"\"\" id = UUID() target_type =", "= Text() review_upvotes = Array(base_column = BigInt(), default = []) review_downvotes = Array(base_column", "0, choices = enums.LongDescType) long_description = Text() votes = BigInt(default = 0) guild_count", "= 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type", "= \"Discord Integration Text\") website = Text() discord = Text() banner_card = Text()", "webhook = Text() bot_library = Text() css = Text(default = \"\") prefix =", "voted\") description = Text(default = \"This user prefers to be an enigma\") badges", "piccolo.columns.readable import Readable from piccolo.table import Table from modules.models import enums class Vanity(Table,", "ones currently on profiles are special and manually handled without using this column.\")", "= True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When", "user prefers to be an enigma\") badges = Array(base_column = Text(), help_text =", "Text() banner_page = Text() github = Text() donate = Text() privacy_policy = Text()", "Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url =", "Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column = BigInt(), default=[])", "webhook_type = Integer(choices = enums.WebhookType) webhook = Text() bot_library = Text() css =", "Text(default = \"\") state = Integer(default = 0, choices = enums.UserState) coins =", "Vanity(Table, tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key = True) redirect = BigInt()", "True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the", "Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt() state = Integer(choices = enums.BotState,", "import datetime from piccolo.columns.column_types import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret,", "class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user has last voted\")", "datetime from piccolo.columns.column_types import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text,", "= Boolean(default = False) api_token = Text() js_allowed = Boolean(default = True) invite", "bot_library = Text() css = Text(default = \"\") prefix = Varchar(length = 13)", "stars a bot has\") review_text = Text() review_upvotes = Array(base_column = BigInt(), default", "BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user has last", "Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table import Table from modules.models import", "= Text(primary_key = True) redirect = BigInt() class User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text", "your own through this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id =", "= \"\") prefix = Varchar(length = 13) di_text = Text(help_text = \"Discord Integration", "donate = Text() privacy_policy = Text() nsfw = Boolean(default = False) api_token =", "has last voted\") description = Text(default = \"This user prefers to be an", "an enigma\") badges = Array(base_column = Text(), help_text = \"Custom User Badges. The", "= Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook = Text() bot_library", "target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text =", "= datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook = Text() bot_library = Text()", "di_text = Text(help_text = \"Discord Integration Text\") website = Text() discord = Text()", "enums.BotState, default = 1) description = Text() long_description_type = Integer(default = 0, choices", "are special and manually handled without using this column.\") username = Text() profile_css", "= Text() profile_css = Text(default = \"\") user_css = Text(default = \"\") state", "User(Table, tablename=\"users\"): vote_epoch = Timestamptz(help_text = \"When the user has last voted\") description", "Array(base_column = Integer()) user_count = BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now())", "enums.LongDescType) long_description = Text() votes = BigInt(default = 0) guild_count = BigInt(default =", "import Readable from piccolo.table import Table from modules.models import enums class Vanity(Table, tablename=\"vanity\"):", "javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt()", "tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never", "Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table import Table from modules.models", "Timestamptz(help_text = \"When the user has last voted\") description = Text(default = \"This", "Text() discord = Text() banner_card = Text() banner_page = Text() github = Text()", "Text() privacy_policy = Text() nsfw = Boolean(default = False) api_token = Text() js_allowed", "profiles are special and manually handled without using this column.\") username = Text()", "handled without using this column.\") username = Text() profile_css = Text(default = \"\")", "BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now())", "False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your own through this", "banner_page = Text() github = Text() donate = Text() privacy_policy = Text() nsfw", "tablename=\"reviews\"): \"\"\"Never ever make reviews on your own through this panel\"\"\" id =", "= Text(null = False) class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your", "class Review(Table, tablename=\"reviews\"): \"\"\"Never ever make reviews on your own through this panel\"\"\"", "= Text() invite_amount = Integer(default = 0) features = Array(base_column = Text(), default", "enigma\") badges = Array(base_column = Text(), help_text = \"Custom User Badges. The ones", "datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook = Text() bot_library = Text() css", "import (UUID, Array, BigInt, Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from", "Boolean, Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from", "The ones currently on profiles are special and manually handled without using this", "guild_count = BigInt(default = 0) shard_count = BigInt(default = 0) shards = Array(base_column", "website = Text() discord = Text() banner_card = Text() banner_page = Text() github", "description = Text(default = \"This user prefers to be an enigma\") badges =", "flagged = Boolean(default=False) epoch = Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[])", "= False) api_token = Text() js_allowed = Boolean(default = True) invite = Text()", "Float(help_text = \"Amount of stars a bot has\") review_text = Text() review_upvotes =", "profile_css = Text(default = \"\") user_css = Text(default = \"\") state = Integer(default", "features = Array(base_column = Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id =", "= ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars a bot has\") review_text", "Text() css = Text(default = \"\") prefix = Varchar(length = 13) di_text =", "on profiles are special and manually handled without using this column.\") username =", "= Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag =", "= \"\") user_css = Text(default = \"\") state = Integer(default = 0, choices", "default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null =", "user has last voted\") description = Text(default = \"This user prefers to be", "created_at = Timestamptz(default = datetime.datetime.now()) webhook_type = Integer(choices = enums.WebhookType) webhook = Text()", "= 0) js_allowed = Boolean(default = False, help_text = \"Is the user allowed", "bot has\") review_text = Text() review_upvotes = Array(base_column = BigInt(), default = [])", "= True) invite = Text() invite_amount = Integer(default = 0) features = Array(base_column", "User Badges. The ones currently on profiles are special and manually handled without", "privacy_policy = Text() nsfw = Boolean(default = False) api_token = Text() js_allowed =", "own through this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt()", "= 0, choices = enums.UserState) coins = Integer(default = 0) js_allowed = Boolean(default", "[]) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null = False) class", "BigInt(default = 0) guild_count = BigInt(default = 0) shard_count = BigInt(default = 0)", "= Timestamptz(help_text = \"When the user has last voted\") description = Text(default =", "manually handled without using this column.\") username = Text() profile_css = Text(default =", "class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt() state = Integer(choices =", "0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at = Timestamptz(default = datetime.datetime.now()) webhook_type =", "Integer(default = 0) js_allowed = Boolean(default = False, help_text = \"Is the user", "Varchar) from piccolo.columns.readable import Readable from piccolo.table import Table from modules.models import enums", "Integer(choices = enums.WebhookType) webhook = Text() bot_library = Text() css = Text(default =", "= Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False) @classmethod", "= BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount of stars a", "BigInt() state = Integer(choices = enums.BotState, default = 1) description = Text() long_description_type", "BigInt(), default = []) review_downvotes = Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False)", "Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table import Table from", "panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User)", "= Float(help_text = \"Amount of stars a bot has\") review_text = Text() review_upvotes", "\"Custom User Badges. The ones currently on profiles are special and manually handled", "tablename=\"vanity\"): type = Integer() vanity_url = Text(primary_key = True) redirect = BigInt() class", "user allowed to use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached =", "Text() github = Text() donate = Text() privacy_policy = Text() nsfw = Boolean(default", "choices = enums.LongDescType) long_description = Text() votes = BigInt(default = 0) guild_count =", "Integer(choices = enums.BotState, default = 1) description = Text() long_description_type = Integer(default =", "Boolean(default = False) api_token = Text() js_allowed = Boolean(default = True) invite =", "the user allowed to use javascript\") api_token = Text() class Bot(Table, tablename=\"bots\"): username_cached", "BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null = False) class Review(Table, tablename=\"reviews\"):", "of stars a bot has\") review_text = Text() review_upvotes = Array(base_column = BigInt(),", "= Text() long_description_type = Integer(default = 0, choices = enums.LongDescType) long_description = Text()", "= Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount", "Text() verifier = BigInt() state = Integer(choices = enums.BotState, default = 1) description", "0) features = Array(base_column = Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id", "[]) review_downvotes = Array(base_column = BigInt(), default=[]) flagged = Boolean(default=False) epoch = Array(base_column", "\"Amount of stars a bot has\") review_text = Text() review_upvotes = Array(base_column =", "Text(), default = []) class BotTag(Table, tablename=\"bot_tags\"): bot_id = ForeignKey(references=Bot) tag = Text(null", "invite_amount = Integer(default = 0) features = Array(base_column = Text(), default = [])", "this panel\"\"\" id = UUID() target_type = Integer(choices=enums.ReviewType) target_id = BigInt() user_id =", "Text() js_allowed = Boolean(default = True) invite = Text() invite_amount = Integer(default =", "Integer()) user_count = BigInt(default = 0) last_stats_post = Timestamptz(default = datetime.datetime.now()) created_at =", "= 0) shard_count = BigInt(default = 0) shards = Array(base_column = Integer()) user_count", "= Text() donate = Text() privacy_policy = Text() nsfw = Boolean(default = False)", "= Array(base_column = Text(), help_text = \"Custom User Badges. The ones currently on", "the user has last voted\") description = Text(default = \"This user prefers to", "Text() long_description_type = Integer(default = 0, choices = enums.LongDescType) long_description = Text() votes", "description = Text() long_description_type = Integer(default = 0, choices = enums.LongDescType) long_description =", "Integer(choices=enums.ReviewType) target_id = BigInt() user_id = ForeignKey(references=User) star_rating = Float(help_text = \"Amount of", "review_text = Text() review_upvotes = Array(base_column = BigInt(), default = []) review_downvotes =", "js_allowed = Boolean(default = True) invite = Text() invite_amount = Integer(default = 0)", "votes = BigInt(default = 0) guild_count = BigInt(default = 0) shard_count = BigInt(default", "= Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt() state =", "Float, ForeignKey, Integer, Secret, Text, Timestamptz, Varchar) from piccolo.columns.readable import Readable from piccolo.table", "Text() class Bot(Table, tablename=\"bots\"): username_cached = Text() verifier = BigInt() state = Integer(choices", "= Array(base_column = BigInt(), default = []) review_downvotes = Array(base_column = BigInt(), default=[])", "epoch = Array(base_column = BigInt(), default=[]) replies = Array(base_column=UUID(), default=[]) reply = Boolean(default=False)" ]
[ "nome = input('Qual é seu nome: ') print(nome or 'Você não digitou nada!')", "condicional com operador OR \"\"\" nome = input('Qual é seu nome: ') print(nome", "OR \"\"\" nome = input('Qual é seu nome: ') print(nome or 'Você não", "\"\"\" nome = input('Qual é seu nome: ') print(nome or 'Você não digitou", "operador OR \"\"\" nome = input('Qual é seu nome: ') print(nome or 'Você", "\"\"\" Expressão condicional com operador OR \"\"\" nome = input('Qual é seu nome:", "com operador OR \"\"\" nome = input('Qual é seu nome: ') print(nome or", "Expressão condicional com operador OR \"\"\" nome = input('Qual é seu nome: ')" ]
[ "result result = intersection([1, 2, 2, 3, 3, 4], [2, 3, 3]) assert", "len(y): if x[idx_x] == y[idx_y] and (not result or result[-1] != x[idx_x]): result.append(x[idx_x])", "result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y +=", "idx_y += 1 else: idx_x += 1 return result result = intersection([1, 2,", "3, 3, 4], [4]) assert result == [4] result = intersection([1, 2, 2,", "result = [] idx_x = idx_y = 0 while idx_x < len(x) and", "y: List[int]) -> List[int]: result = [] idx_x = idx_y = 0 while", "[2, 3] result = intersection([1, 2, 2, 3, 3, 4], [4]) assert result", "typing import List def intersection(x: List[int], y: List[int]) -> List[int]: result = []", "import List def intersection(x: List[int], y: List[int]) -> List[int]: result = [] idx_x", "1 else: idx_x += 1 return result result = intersection([1, 2, 2, 3,", "2, 3, 3, 4], [4]) assert result == [4] result = intersection([1, 2,", "= intersection([1, 2, 2, 3, 3, 4], [2, 3, 3]) assert result ==", "<filename>elements-of-programming-interviews/14.1.sorted-array-intersection.py from typing import List def intersection(x: List[int], y: List[int]) -> List[int]: result", "List def intersection(x: List[int], y: List[int]) -> List[int]: result = [] idx_x =", "== [2, 3] result = intersection([1, 2, 2, 3, 3, 4], [4]) assert", "idx_x = idx_y = 0 while idx_x < len(x) and idx_y < len(y):", "= idx_y = 0 while idx_x < len(x) and idx_y < len(y): if", "len(x) and idx_y < len(y): if x[idx_x] == y[idx_y] and (not result or", "+= 1 return result result = intersection([1, 2, 2, 3, 3, 4], [2,", "idx_x += 1 idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y += 1", "= 0 while idx_x < len(x) and idx_y < len(y): if x[idx_x] ==", "y[idx_y] and (not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y", "def intersection(x: List[int], y: List[int]) -> List[int]: result = [] idx_x = idx_y", "intersection([1, 2, 2, 3, 3, 4], [2, 3, 3]) assert result == [2,", "return result result = intersection([1, 2, 2, 3, 3, 4], [2, 3, 3])", "if x[idx_x] == y[idx_y] and (not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x", "3, 4], [2, 3, 3]) assert result == [2, 3] result = intersection([1,", "!= x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif x[idx_x] > y[idx_y]:", "[4] result = intersection([1, 2, 2, 3, 3, 4], [5]) assert result ==", "[4]) assert result == [4] result = intersection([1, 2, 2, 3, 3, 4],", "List[int]) -> List[int]: result = [] idx_x = idx_y = 0 while idx_x", "== y[idx_y] and (not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1", "-> List[int]: result = [] idx_x = idx_y = 0 while idx_x <", "[2, 3, 3]) assert result == [2, 3] result = intersection([1, 2, 2,", "= intersection([1, 2, 2, 3, 3, 4], [4]) assert result == [4] result", "1 idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x", "+= 1 else: idx_x += 1 return result result = intersection([1, 2, 2,", "> y[idx_y]: idx_y += 1 else: idx_x += 1 return result result =", "2, 3, 3, 4], [2, 3, 3]) assert result == [2, 3] result", "3, 3, 4], [2, 3, 3]) assert result == [2, 3] result =", "assert result == [4] result = intersection([1, 2, 2, 3, 3, 4], [5])", "[] idx_x = idx_y = 0 while idx_x < len(x) and idx_y <", "3]) assert result == [2, 3] result = intersection([1, 2, 2, 3, 3,", "else: idx_x += 1 return result result = intersection([1, 2, 2, 3, 3,", "result = intersection([1, 2, 2, 3, 3, 4], [2, 3, 3]) assert result", "intersection([1, 2, 2, 3, 3, 4], [4]) assert result == [4] result =", "from typing import List def intersection(x: List[int], y: List[int]) -> List[int]: result =", "idx_x += 1 return result result = intersection([1, 2, 2, 3, 3, 4],", "+= 1 idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y += 1 else:", "< len(y): if x[idx_x] == y[idx_y] and (not result or result[-1] != x[idx_x]):", "+= 1 elif x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x += 1", "(not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1", "idx_y < len(y): if x[idx_x] == y[idx_y] and (not result or result[-1] !=", "3, 3]) assert result == [2, 3] result = intersection([1, 2, 2, 3,", "idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x +=", "List[int], y: List[int]) -> List[int]: result = [] idx_x = idx_y = 0", "result == [2, 3] result = intersection([1, 2, 2, 3, 3, 4], [4])", "y[idx_y]: idx_y += 1 else: idx_x += 1 return result result = intersection([1,", "2, 2, 3, 3, 4], [2, 3, 3]) assert result == [2, 3]", "result = intersection([1, 2, 2, 3, 3, 4], [5]) assert result == []", "2, 2, 3, 3, 4], [4]) assert result == [4] result = intersection([1,", "4], [4]) assert result == [4] result = intersection([1, 2, 2, 3, 3,", "intersection(x: List[int], y: List[int]) -> List[int]: result = [] idx_x = idx_y =", "== [4] result = intersection([1, 2, 2, 3, 3, 4], [5]) assert result", "idx_x < len(x) and idx_y < len(y): if x[idx_x] == y[idx_y] and (not", "elif x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x += 1 return result", "result = intersection([1, 2, 2, 3, 3, 4], [4]) assert result == [4]", "result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif x[idx_x] >", "3, 4], [4]) assert result == [4] result = intersection([1, 2, 2, 3,", "and idx_y < len(y): if x[idx_x] == y[idx_y] and (not result or result[-1]", "x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif x[idx_x] > y[idx_y]: idx_y", "while idx_x < len(x) and idx_y < len(y): if x[idx_x] == y[idx_y] and", "0 while idx_x < len(x) and idx_y < len(y): if x[idx_x] == y[idx_y]", "assert result == [2, 3] result = intersection([1, 2, 2, 3, 3, 4],", "idx_y = 0 while idx_x < len(x) and idx_y < len(y): if x[idx_x]", "result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif", "result == [4] result = intersection([1, 2, 2, 3, 3, 4], [5]) assert", "and (not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y +=", "x[idx_x] == y[idx_y] and (not result or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x +=", "4], [2, 3, 3]) assert result == [2, 3] result = intersection([1, 2,", "1 elif x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x += 1 return", "< len(x) and idx_y < len(y): if x[idx_x] == y[idx_y] and (not result", "= [] idx_x = idx_y = 0 while idx_x < len(x) and idx_y", "or result[-1] != x[idx_x]): result.append(x[idx_x]) idx_x += 1 idx_y += 1 elif x[idx_x]", "1 return result result = intersection([1, 2, 2, 3, 3, 4], [2, 3,", "x[idx_x] > y[idx_y]: idx_y += 1 else: idx_x += 1 return result result", "3] result = intersection([1, 2, 2, 3, 3, 4], [4]) assert result ==", "List[int]: result = [] idx_x = idx_y = 0 while idx_x < len(x)" ]
[ "bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver,", "format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process,", "bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace,", "bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info,", "3. A Python module for semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated", "A Python module for semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated import", "<gh_stars>100-1000 \"\"\" semver package major release 3. A Python module for semantic versioning.", "package major release 3. A Python module for semantic versioning. Simplifies comparing versions.", "for semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated import ( bump_build, bump_major,", "Version, VersionInfo from .__about__ import ( __version__, __author__, __maintainer__, __author_email__, __description__, __maintainer_email__, SEMVER_SPEC_VERSION,", "major release 3. A Python module for semantic versioning. Simplifies comparing versions. \"\"\"", "release 3. A Python module for semantic versioning. Simplifies comparing versions. \"\"\" from", "bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare,", "bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump,", "._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver,", "semver package major release 3. A Python module for semantic versioning. Simplifies comparing", "Python module for semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated import (", "semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor,", "cmd_check, createparser, process, main, ) from .version import Version, VersionInfo from .__about__ import", ".version import Version, VersionInfo from .__about__ import ( __version__, __author__, __maintainer__, __author_email__, __description__,", "module for semantic versioning. Simplifies comparing versions. \"\"\" from ._deprecated import ( bump_build,", "\"\"\" semver package major release 3. A Python module for semantic versioning. Simplifies", "compare, finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check,", "from .version import Version, VersionInfo from .__about__ import ( __version__, __author__, __maintainer__, __author_email__,", "cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from .version import Version, VersionInfo", "parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from .version", "parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from .version import", "max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, )", "min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from", "main, ) from .version import Version, VersionInfo from .__about__ import ( __version__, __author__,", "cmd_nextver, cmd_check, createparser, process, main, ) from .version import Version, VersionInfo from .__about__", "comparing versions. \"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare,", "VersionInfo from .__about__ import ( __version__, __author__, __maintainer__, __author_email__, __description__, __maintainer_email__, SEMVER_SPEC_VERSION, )", "versioning. Simplifies comparing versions. \"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch,", "Simplifies comparing versions. \"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease,", ") from .version import Version, VersionInfo from .__about__ import ( __version__, __author__, __maintainer__,", "import Version, VersionInfo from .__about__ import ( __version__, __author__, __maintainer__, __author_email__, __description__, __maintainer_email__,", "from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match,", "process, main, ) from .version import Version, VersionInfo from .__about__ import ( __version__,", "match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main,", "createparser, process, main, ) from .version import Version, VersionInfo from .__about__ import (", "finalize_version, format_version, match, max_ver, min_ver, parse, parse_version_info, replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser,", "versions. \"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version,", "\"\"\" from ._deprecated import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version,", "import ( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver,", "( bump_build, bump_major, bump_minor, bump_patch, bump_prerelease, compare, finalize_version, format_version, match, max_ver, min_ver, parse,", "cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from .version import Version, VersionInfo from", "replace, cmd_bump, cmd_compare, cmd_nextver, cmd_check, createparser, process, main, ) from .version import Version," ]
[ "Creating the term dictionary of our courpus, where every unique term is assigned", "nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import gensim from gensim", "topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] #", "= [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array =", "# Creating the object for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel", "of our courpus, where every unique term is assigned an index. dictionary =", "np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude =", "def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data", "lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\"", "for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free =", "using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch", "and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set]", "courpus, where every unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean) #", "import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import gensim from gensim import", "exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses", "= 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA model using", "for ch in doc if ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\"", "exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed = \"", "in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed =", "index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document Term", "# Converting list of documents (corpus) into Document Term Matrix using dictionary prepared", "stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\")", "x in range(n_topics)] for itr in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr,", "list of documents (corpus) into Document Term Matrix using dictionary prepared above. doc_term_matrix", "\" \".join([i for i in stemmed.split() if i not in stop]) return stop_free", "doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist))", "(corpus) into Document Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for", "ch in doc if ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \"", "= [[] for x in range(n_topics)] for itr in range(len(dist_array)): for top, weight", "if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set =", "import gensim from gensim import corpora from gensim.test.utils import datapath import numpy as", "above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # Loading the LDA model", "our courpus, where every unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean)", "the term dictionary of our courpus, where every unique term is assigned an", "Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above.", "for word in lemmatized.split()) stop_free = \" \".join([i for i in stemmed.split() if", "stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma =", "# Adapted from: # https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/ import read_bibtex import os, shutil from nltk.corpus import", "Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc", "import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import", "os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import", "dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document Term Matrix", "word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free =", "punc_free = ''.join(ch for ch in doc if ch not in exclude) lemmatized", "\".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \" \".join([i for i in stemmed.split()", "from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import gensim from", "= set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics", "assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into", "400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA model using gensim", "lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word)", "stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \" \".join([i for", "gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch in", "unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of", "stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation)", "set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics =", "import read_bibtex import os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer", "= \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \" \".join([i for i", "of documents (corpus) into Document Term Matrix using dictionary prepared above. doc_term_matrix =", "LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc topic_dist", "each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\",", "stemmed.split() if i not in stop]) return stop_free def main(): if result_dir in", "read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set] # Creating the term dictionary", "in range(n_topics)] for itr in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight))", "np.array(topic_dist) transpose_array = [[] for x in range(n_topics)] for itr in range(len(dist_array)): for", "= ''.join(ch for ch in doc if ch not in exclude) lemmatized =", "for i in stemmed.split() if i not in stop]) return stop_free def main():", "Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each", "not in stop]) return stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir)", "doc_clean] # Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution", "gensim.test.utils import datapath import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\")", "punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \" \".join([i", "stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean", "result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from)", "in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \"", "for doc in doc_set] # Creating the term dictionary of our courpus, where", "doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for", "corpora from gensim.test.utils import datapath import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\")", "Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for x in", "shutil from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer", "year_from=1980 # Creating the object for LDA model using gensim library Lda =", "in doc_clean] # Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic", "for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results", "model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc topic_dist =", "[ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist)", "Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] #", "# https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/ import read_bibtex import os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet", "word in lemmatized.split()) stop_free = \" \".join([i for i in stemmed.split() if i", "= read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set] # Creating the term", "for itr in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row", "PorterStemmer import string import gensim from gensim import corpora from gensim.test.utils import datapath", "return stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and", "PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the", "30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA", "doc in doc_clean] # Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer", "prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # Loading the LDA", "in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[]", "data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set] # Creating", "as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude", "Adapted from: # https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/ import read_bibtex import os, shutil from nltk.corpus import stopwords", "nltk.stem.porter import PorterStemmer import string import gensim from gensim import corpora from gensim.test.utils", "not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed", "= corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document Term Matrix using", "= np.array(topic_dist) transpose_array = [[] for x in range(n_topics)] for itr in range(len(dist_array)):", "numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\")", "ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object", "model using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for", "= \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for", "stop]) return stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read", "corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document Term Matrix using dictionary", "for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array", "clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set] #", "library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch in doc", "in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x: x[1], reverse=True) np.save(\"./\"+result_dir+\"/all_transpose\",", "results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for x in range(n_topics)]", "range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda", "where every unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting", "exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses =", "for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free", "Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch in doc if", "in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean", "stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer =", "\" for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in lemmatized.split())", "[clean(doc).split() for doc in doc_set] # Creating the term dictionary of our courpus,", "for doc in doc_clean] # Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") #", "for x in range(n_topics)] for itr in range(len(dist_array)): for top, weight in dist_array[itr]:", "import datapath import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\")", "in lemmatized.split()) stop_free = \" \".join([i for i in stemmed.split() if i not", "from: # https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/ import read_bibtex import os, shutil from nltk.corpus import stopwords from", "documents (corpus) into Document Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc)", "in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array:", "lemmatized.split()) stop_free = \" \".join([i for i in stemmed.split() if i not in", "main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set", "dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # Loading the", "# Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for x", "every unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list", "doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in doc_set] # Creating the", "# Infer topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in", "into Document Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc", "doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array =", "in stemmed.split() if i not in stop]) return stop_free def main(): if result_dir", "topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save results np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array", "= 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for", "= [dictionary.doc2bow(doc) for doc in doc_clean] # Loading the LDA model ldamodel =", "\".join([i for i in stemmed.split() if i not in stop]) return stop_free def", "os.mkdir(\"./\"+result_dir) # Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for", "result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA model using gensim library", "an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document", "import corpora from gensim.test.utils import datapath import numpy as np stop = set(stopwords.words('english'))", "doc_clean = [clean(doc).split() for doc in doc_set] # Creating the term dictionary of", "doc_set] # Creating the term dictionary of our courpus, where every unique term", "gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch in doc if ch not", "WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980", "clean(doc): punc_free = ''.join(ch for ch in doc if ch not in exclude)", "[dictionary.doc2bow(doc) for doc in doc_clean] # Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\")", "datapath import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\")", "import PorterStemmer import string import gensim from gensim import corpora from gensim.test.utils import", "# Loading the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for", "dictionary of our courpus, where every unique term is assigned an index. dictionary", "range(n_topics)] for itr in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for", "i in stemmed.split() if i not in stop]) return stop_free def main(): if", "in stop]) return stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) #", "exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer()", "stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import gensim", "doc in doc_set] # Creating the term dictionary of our courpus, where every", "top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x: x[1],", "set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\")", "stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma", "stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\")", "gensim import corpora from gensim.test.utils import datapath import numpy as np stop =", "doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # Loading the LDA model ldamodel", "read_bibtex import os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from", "i not in stop]) return stop_free def main(): if result_dir in os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir)", "stop_free = \" \".join([i for i in stemmed.split() if i not in stop])", "stemmer = PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 #", "if ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in", "term dictionary of our courpus, where every unique term is assigned an index.", "distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean] # Save", "WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string import gensim from gensim import corpora", "is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus)", "def clean(doc): punc_free = ''.join(ch for ch in doc if ch not in", "from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import", "exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses = 400", "os.listdir(\".\"): shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean =", "shutil.rmtree(\"./\"+result_dir) os.mkdir(\"./\"+result_dir) # Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split()", "Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]", "the object for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc):", "stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer()", "the LDA model ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc", "ldamodel = Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc))", "from gensim import corpora from gensim.test.utils import datapath import numpy as np stop", "Document Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in", "LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch", "dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x: x[1], reverse=True) np.save(\"./\"+result_dir+\"/all_transpose\", np.array(transpose_array))", "doc if ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word", "npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA model", "stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer", "if i not in stop]) return stop_free def main(): if result_dir in os.listdir(\".\"):", "\" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word", "[[] for x in range(n_topics)] for itr in range(len(dist_array)): for top, weight in", "in doc if ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for", "from gensim.test.utils import datapath import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\")", "weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x: x[1], reverse=True)", "\" \".join(stemmer.stem(word) for word in lemmatized.split()) stop_free = \" \".join([i for i in", "model_dir=\"model_all_500_30\" year_from=1980 # Creating the object for LDA model using gensim library Lda", "transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x: x[1], reverse=True) np.save(\"./\"+result_dir+\"/all_transpose\", np.array(transpose_array)) main()", "ch not in exclude) lemmatized = \" \".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split())", "= PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\" year_from=1980 # Creating", "for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in transpose_array: row.sort(key=lambda x:", "Infer topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for doc in doc_clean]", "term is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents", "# Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc", "= WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30 npasses = 400 result_dir=\"doc_results_all_500_30\" model_dir=\"model_all_500_30\"", "https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/ import read_bibtex import os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet import", "import os, shutil from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter", "''.join(ch for ch in doc if ch not in exclude) lemmatized = \"", "import numpy as np stop = set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\")", "transpose_array = [[] for x in range(n_topics)] for itr in range(len(dist_array)): for top,", "nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.porter import PorterStemmer import string", "in doc_set] # Creating the term dictionary of our courpus, where every unique", "np.save(\"./\"+result_dir+\"/all\", np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for x in range(n_topics)] for", "= Lda.load(\"./\"+model_dir+\"/all\") # Infer topic distribution for each doc topic_dist = [ldamodel.get_document_topics(dictionary.doc2bow(doc)) for", "# Creating the term dictionary of our courpus, where every unique term is", "= set(stopwords.words('english')) stop.add(\"exist\") stop.add(\"because\") stop.add(\"via\") stop.add(\"interest\") stop.add(\"therefore\") stop.add(\"hence\") stop.add(\"this\") exclude = set(string.punctuation) exclude.add(\"-\")", "np.array(topic_dist)) dist_array = np.array(topic_dist) transpose_array = [[] for x in range(n_topics)] for itr", "gensim from gensim import corpora from gensim.test.utils import datapath import numpy as np", "string import gensim from gensim import corpora from gensim.test.utils import datapath import numpy", "itr in range(len(dist_array)): for top, weight in dist_array[itr]: transpose_array[top].append((itr, weight)) for row in", "Creating the object for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel def", "= \" \".join([i for i in stemmed.split() if i not in stop]) return", "= [clean(doc).split() for doc in doc_set] # Creating the term dictionary of our", "using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # Loading", "dist_array = np.array(topic_dist) transpose_array = [[] for x in range(n_topics)] for itr in", "exclude.add(\"-\") exclude.add(\"_\") exclude.add(\".\") exclude.add(\";\") lemma = WordNetLemmatizer() stemmer = PorterStemmer() ntopics = 30", "import string import gensim from gensim import corpora from gensim.test.utils import datapath import", "from nltk.stem.porter import PorterStemmer import string import gensim from gensim import corpora from", "Read and clean data doc_set = read_bibtex.bibtex_tostring_from(year_from) doc_clean = [clean(doc).split() for doc in", "\".join(lemma.lemmatize(word)+\" \" for word in punc_free.lower().split()) stemmed = \" \".join(stemmer.stem(word) for word in", "object for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel def clean(doc): punc_free", "= gensim.models.ldamodel.LdaModel def clean(doc): punc_free = ''.join(ch for ch in doc if ch" ]
[ "\"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake", "CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\",", "CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings):", "= CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not", "not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"), run_environment=True) self.run(self.build_folder + \"/Test_App-x86_64.AppImage --appimage-extract-and-run\")", "\"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def", "\"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self):", "cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"), run_environment=True)", "cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if", "class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") #", "if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"), run_environment=True) self.run(self.build_folder + \"/Test_App-x86_64.AppImage", "# build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder +", "ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources =", "= (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure()", "= self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\"", "= (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"]", "\"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder", "\"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder +", "from conans import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\",", "os from conans import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\",", "settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires =", "(\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\")", "def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"), run_environment=True) self.run(self.build_folder", "conans import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\"", "(\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] =", "test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"), run_environment=True) self.run(self.build_folder +", "import os from conans import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\",", "import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources", "AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires", "= \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\")", "cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool", "tools class AppimagetoolinstallerTestConan(ConanFile): settings = \"os\", \"compiler\", \"build_type\", \"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\")", "build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\"", "\"arch\" exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake =", "exports_sources = (\"appimage.svg\", \"org.appimagecraft.TestApp.desktop\") # build_requires = (\"cmake_installer/3.10.0@conan/stable\") def build(self): cmake = CMake(self)", "def build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def", "<reponame>appimage-conan-community/appimagetool_installer import os from conans import ConanFile, CMake, tools class AppimagetoolinstallerTestConan(ConanFile): settings =", "+ \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder", "cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" % (self.build_folder + \"/AppDir\"),", "build(self): cmake = CMake(self) cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self):", "self.build_folder + \"/AppDir\" cmake.configure() cmake.build(target=\"install\") def test(self): if not tools.cross_building(self.settings): self.run(\"appimagetool %s\" %" ]
[ "= os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(), Split([ (", "Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]),", "<filename>docs/examples/tutorial/2_split/main3.py from __future__ import print_function import os from lena.core import Sequence, Split, Source", "lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable from read_data import ReadData def", "import Variable from read_data import ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\")", "from lena.core import Sequence, Split, Source from lena.structures import Histogram from lena.math import", "10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), )", "MakeFilename, RenderLaTeX from lena.variables import Variable from read_data import ReadData def main(): data_file", "from __future__ import print_function import os from lena.core import Sequence, Split, Source from", "( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec:", "10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results", "Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\",", "from lena.math import mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output", "os from lena.core import Sequence, Split, Source from lena.structures import Histogram from lena.math", "( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write,", "lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10,", "LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable from read_data", "import Sequence, Split, Source from lena.structures import Histogram from lena.math import mesh from", "import ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s", "import print_function import os from lena.core import Sequence, Split, Source from lena.structures import", "ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s =", "RenderLaTeX from lena.variables import Variable from read_data import ReadData def main(): data_file =", "Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda", "\"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda", "vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(),", "ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable", "read_data import ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\")", "Histogram from lena.math import mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from", "from read_data import ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write =", "RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res in results:", "ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\",", "10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"),", "ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res", "vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10),", "), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda", "vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)),", "Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ),", "vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10),", "vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write,", "write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res in results: print(res) if", "import os from lena.core import Sequence, Split, Source from lena.structures import Histogram from", "Variable from read_data import ReadData def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write", "PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable from read_data import", "\"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec:", "Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(),", "\"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res in results: print(res)", "from lena.structures import Histogram from lena.math import mesh from lena.output import ToCSV, Write,", "lena.structures import Histogram from lena.math import mesh from lena.output import ToCSV, Write, LaTeXToPDF,", "write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res in", "import Histogram from lena.math import mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG", "write = Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]),", "vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)),", "10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\",", "( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec:", "import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables import", "lena.math import mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import", "def main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence(", ") results = s.run([data_file]) for res in results: print(res) if __name__ == \"__main__\":", "lena.core import Sequence, Split, Source from lena.structures import Histogram from lena.math import mesh", "data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(), Split([", "Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ),", "lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"),", "Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10),", "), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(),", "PDFToPNG(), ) results = s.run([data_file]) for res in results: print(res) if __name__ ==", "= Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ),", "Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), (", "s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)),", "print_function import os from lena.core import Sequence, Split, Source from lena.structures import Histogram", "= Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10,", "from lena.variables import Variable from read_data import ReadData def main(): data_file = os.path.join(\"..\",", "__future__ import print_function import os from lena.core import Sequence, Split, Source from lena.structures", "import mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename,", "10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), (", "lambda vec: vec[1]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10,", "10), 10)), ), ( Variable(\"z\", lambda vec: vec[2]), Histogram(mesh((-10, 10), 10)), ), ]),", "lena.variables import Variable from read_data import ReadData def main(): data_file = os.path.join(\"..\", \"data\",", "os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(), Split([ ( Variable(\"x\",", "Variable(\"x\", lambda vec: vec[0]), Histogram(mesh((-10, 10), 10)), ), ( Variable(\"y\", lambda vec: vec[1]),", "import MakeFilename, RenderLaTeX from lena.variables import Variable from read_data import ReadData def main():", "Source from lena.structures import Histogram from lena.math import mesh from lena.output import ToCSV,", "from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from", "results = s.run([data_file]) for res in results: print(res) if __name__ == \"__main__\": main()", "Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable from", "Sequence, Split, Source from lena.structures import Histogram from lena.math import mesh from lena.output", "from lena.output import MakeFilename, RenderLaTeX from lena.variables import Variable from read_data import ReadData", "Split, Source from lena.structures import Histogram from lena.math import mesh from lena.output import", "lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX from lena.variables", "LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for res in results: print(res) if __name__", "main(): data_file = os.path.join(\"..\", \"data\", \"normal_3d.csv\") write = Write(\"output\") s = Sequence( ReadData(),", "MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file]) for", "), ]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results =", "]), MakeFilename(\"{{variable.name}}\"), ToCSV(), write, RenderLaTeX(\"histogram_1d.tex\", \"templates\"), write, LaTeXToPDF(), PDFToPNG(), ) results = s.run([data_file])", "mesh from lena.output import ToCSV, Write, LaTeXToPDF, PDFToPNG from lena.output import MakeFilename, RenderLaTeX" ]
[ "information returned from get_rpaths_macos(). Returns a mapping from original to resolved library paths", "LC_LOAD_DYLIB: Returns a list of shared object library dependencies, with one shared object", "= PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type == LC_RPATH: if key", "of symbolic to resolved library dependencies of the given binary. See resolve_library_paths_macos(). \"\"\"", "from dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD", "metadata from rpath dump line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type ==", "DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src", "= 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\"", "a map of symbolic to resolved library dependencies of the given binary. See", "version, OS, and architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str", "output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers() for macOS. 'cmd_type'", "objdump output per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except", "We have to set the RUNPATH of the shared objects as well for", "return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB,", "are not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+|", "config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name,", "set on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No", "re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key", "implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we have the chrpath command", "artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for convenient plumbing of", "if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise", "cluster. The resulting binaries should never # be deployed to run an actual", "by # integration tests using a mini cluster. The resulting binaries should never", "= version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def mkconfig(build_root,", "the runtime host is # patched. ################################################################################ import logging import optparse import os", "(raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to", "and returns an empty map. \"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths:", "ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX =", "the build directory into the artifact directory, and change the rpath of the", "if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest):", "if key == KEY_CMD and val == LC_RPATH: state = PARSING_RPATH continue if", "an appropriate name. Including version, OS, and architecture. \"\"\" if IS_LINUX: os_str =", "= mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config) if __name__ == \"__main__\":", "lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set the RUNPATH", "version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root):", "not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the file with path", "should never # be deployed to run an actual Kudu service, whether in", "license agreements. See the NOTICE file # distributed with this work for additional", "if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported", "output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return [] return", "makes Kudu release binaries relocatable for easy use by # integration tests using", "of shared object library dependencies, with one shared object per entry. They are", "= splits[1] if len(splits) > 1 else None if state == PARSING_NEW_RECORD: if", "for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def", "dependencies in archive...\") config = mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config)", "target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the target", "get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst])", "= PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val =", "relocate_target(target, config): \"\"\" Copy all dependencies of the executable referenced by 'target' from", "# or more contributor license agreements. See the NOTICE file # distributed with", "= objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths)", "in production or # development, because all security dependencies are copied from the", "Make sure we have the chrpath command available in the Linux build. check_for_command('chrpath')", "the rpath information returned from get_rpaths_macos(). Returns a mapping from original to resolved", "Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "stderr and returns an empty map. \"\"\" resolved_paths = {} for raw_lib_path in", "includes kernel and thread # routines that we assume may not be portable", "os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that the specified command is available", "Returns a mapping from original to resolved library paths on success. If any", "target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all dependencies of", "if not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1) artifact_name =", "# regarding copyright ownership. The ASF licenses this file # to you under", "state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return", "= {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR]", "sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if not", "ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] ==", "= 'cmd' KEY_NAME = 'name' KEY_PATH = 'path' # Exclude libraries that are", "relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target", "re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to", "(search_name, resolved_path) in libs.iteritems(): # Filter out libs we don't want to archive.", "err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output", "with path 'src' to path 'dest'. If 'src' is a symlink, the link", "licenses this file # to you under the Apache License, Version 2.0 (the", "can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging from dep_extract", "paths using the rpath information returned from get_rpaths_macos(). Returns a mapping from original", "\"\"\" Make the target relocatable and copy all of its dependencies into the", "re.VERBOSE) # We don't want to ship libSystem because it includes kernel and", "is # patched. ################################################################################ import logging import optparse import os import os.path import", "err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given binary. Returns a", "import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to the", "# Clear the artifact root to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root)", "rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change", "from rpath dump line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB:", "Kudu release binaries relocatable for easy use by # integration tests using a", "in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved", "= \"linux\" elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch =", "if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\") config = mkconfig(build_root,", "absolute filesystem paths using the rpath information returned from get_rpaths_macos(). Returns a mapping", "because it includes kernel and thread # routines that we assume may not", "a configuration map for convenient plumbing of path information. \"\"\" config = {}", "with a warning if no rpath is set on the binary. try: subprocess.check_call(['chrpath',", "%s\", target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation.", "appropriate name. Including version, OS, and architecture. \"\"\" if IS_LINUX: os_str = \"linux\"", "# Exclude libraries that are GPL-licensed and libraries that are not portable #", "parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers() for macOS. 'cmd_type' must be", "search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath in", "update the RUNPATH of the executable itself to look for its # dependencies", "a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\")", "in dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+',", "or implied. See the License for the # specific language governing permissions and", "the given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump)", "of the shared objects as well for transitive # dependencies to be properly", "transitive # dependencies to be properly resolved. $ORIGIN is always relative to the", "\"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not", "to path 'dest'. If 'src' is a symlink, the link will be followed", "Copy the file with path 'src' to path 'dest'. If 'src' is a", "mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config) if __name__ == \"__main__\": main()", "be followed and 'dest' will be written as a plain file. \"\"\" shutil.copyfile(src,", "Create artifact directories, if needed. prep_artifact_dirs(config) # Copy the target into the artifact", "one shared object per entry. They are returned as stored in the MachO", "function that returns a list of rpaths parsed from the given binary. \"\"\"", "subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target %s\", target) raise err def", "Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name'", "path, with one search path per entry. * LC_LOAD_DYLIB: Returns a list of", "return config def prep_artifact_dirs(config): \"\"\" Create any required artifact output directories, if needed.", "symlink, the link will be followed and 'dest' will be written as a", "False for rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path]", "else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version:", "'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH = 'path' # Exclude libraries", "{} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] =", "each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst])", "found when the executable is invoked. \"\"\" # Create artifact directories, if needed.", "raise FileNotFoundError(\"Unable to locate library %s in rpath %s\" % (raw_lib_path, rpaths)) return", "# Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME =", "# artifact directory. return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) < 3:", "use by # integration tests using a mini cluster. The resulting binaries should", "resolved_paths[raw_lib_path] = resolved_path resolved = True break if not resolved: raise FileNotFoundError(\"Unable to", "os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\") config = mkconfig(build_root, artifact_root)", "def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given binary. Returns a list", "it includes kernel and thread # routines that we assume may not be", "import shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the", "macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): #", "'dump' is the output from objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE", "get_rpaths_macos(). Returns a mapping from original to resolved library paths on success. If", "1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values = []", "def check_for_command(command): \"\"\" Ensure that the specified command is available on the PATH.", "2.0 (the # \"License\"); you may not use this file except in compliance", "will be followed and 'dest' will be written as a plain file. \"\"\"", "if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the runtime dependencies. lib_dst =", "break if not resolved: raise FileNotFoundError(\"Unable to locate library %s in rpath %s\"", "\"\"\" Parses the output from objdump_private_headers() for macOS. 'cmd_type' must be one of", "to an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output", "objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from", "the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find", "of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library", "subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable", "target [target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root = sys.argv[1]", "for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have", "RUNPATH of the shared objects as well for transitive # dependencies to be", "RPATH or RUNPATH set on target %s, continuing...\", target) return # Update the", "we have the chrpath command available in the Linux build. check_for_command('chrpath') # Copy", "elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See", "TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT", "information # regarding copyright ownership. The ASF licenses this file # to you", "dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to", "library search path or name for each archived library. modified_search_name = re.sub('^.*/', '@rpath/',", "one # or more contributor license agreements. See the NOTICE file # distributed", "name for each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name,", "check_for_command(command): \"\"\" Ensure that the specified command is available on the PATH. \"\"\"", "service, whether in production or # development, because all security dependencies are copied", "not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\"", "# routines that we assume may not be portable between macOS versions. #", "MachO header, without being first resolved to an absolute path, and may look", "* LC_RPATH: Returns a list containing the rpath search path, with one search", "an error to stderr and returns an empty map. \"\"\" resolved_paths = {}", "= check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\")", "macOS versions. # TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") #", "libraries that are not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread|", "PARSING_NONE values = [] for line in dump: if re.match('^Load command', line): state", "arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory", "libs.iteritems(): # Filter out libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue", "# # Unless required by applicable law or agreed to in writing, #", "from objdump_private_headers() for macOS. 'cmd_type' must be one of the following: * LC_RPATH:", "libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to ship", "lib_dst) # We have to set the RUNPATH of the shared objects as", "for the # specific language governing permissions and limitations # under the License.", "artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src,", "for line in dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits", "between macOS versions. # TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\")", "and will not be updated if the operating system on the runtime host", "def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib'", "of objdump output per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path])", "\"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str = \"osx\" else: raise", "will be written as a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath):", "parsed from the given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def", "re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths", "== KEY_PATH: # Strip trailing metadata from rpath dump line. values.append(val) if state", "on the runtime host is # patched. ################################################################################ import logging import optparse import", "modified_search_name, target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths:", "will be found when the executable is invoked. \"\"\" # Create artifact directories,", "Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we have the chrpath", "== \"Linux\" def check_for_command(command): \"\"\" Ensure that the specified command is available on", "subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\", command) raise", "the RUNPATH of the shared objects as well for transitive # dependencies to", "= 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values = [] for line", "as stored in the MachO header, without being first resolved to an absolute", "may not use this file except in compliance # with the License. You", "'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0]", "when the executable is invoked. \"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config)", "for the specified target. See man chrpath(1). \"\"\" # Continue with a warning", "# running executable. chrpath(lib_dst, NEW_RPATH) # We must also update the RUNPATH of", "with one line of objdump output per record. \"\"\" check_for_command('objdump') try: output =", "in archive...\") config = mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config) if", "command is available on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as", "% (version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration", "Strip trailing metadata from rpath dump line. values.append(val) if state == PARSING_LIB_PATHS and", "under the License. ################################################################################ # This script makes Kudu release binaries relocatable for", "init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB'", "sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does not", "get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact root to ensure a", "BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS", "# Continue with a warning if no rpath is set on the binary.", "os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path or name for each", "relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation.", "mini cluster. The resulting binaries should never # be deployed to run an", "relocatable for easy use by # integration tests using a mini cluster. The", "as err: logging.error(\"Unable to find %s command\", command) raise err def objdump_private_headers(binary_path): \"\"\"", "list of rpaths parsed from the given binary. \"\"\" dump = objdump_private_headers(binary_path) return", "target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target)", "runtime host is # patched. ################################################################################ import logging import optparse import os import", "list of shared object library dependencies, with one shared object per entry. They", "\"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any required artifact output directories, if", "returned as stored in the MachO header, without being first resolved to an", "NOTICE file # distributed with this work for additional information # regarding copyright", "entry. * LC_LOAD_DYLIB: Returns a list of shared object library dependencies, with one", "parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the rpath information returned from get_rpaths_macos().", "# TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys.", "== PARSING_RPATH and cmd_type == LC_RPATH: if key == KEY_PATH: # Strip trailing", "prints an error to stderr and returns an empty map. \"\"\" resolved_paths =", "libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to ship libSystem because it", "library paths on success. If any libraries cannot be resolved, prints an error", "3: print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line", "the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to", "the operating system on the runtime host is # patched. ################################################################################ import logging", "the Apache License, Version 2.0 (the # \"License\"); you may not use this", "os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root", "new_rpath): \"\"\" Change the RPATH or RUNPATH for the specified target. See man", "run an actual Kudu service, whether in production or # development, because all", "= 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS =", "config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all dependencies of the", "artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) #", "to the system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util", "executable. chrpath(lib_dst, NEW_RPATH) # We must also update the RUNPATH of the executable", "'-change', search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath", "language governing permissions and limitations # under the License. ################################################################################ # This script", "the file with path 'src' to path 'dest'. If 'src' is a symlink,", "target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set on target %s,", "one of the following: * LC_RPATH: Returns a list containing the rpath search", "check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return", "(the # \"License\"); you may not use this file except in compliance #", "versions. # TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config", "return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers()", "rpath dump line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if", "libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set the", "mapping from original to resolved library paths on success. If any libraries cannot", "law or agreed to in writing, # software distributed under the License is", "# Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err:", "cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\"", "a warning if no rpath is set on the binary. try: subprocess.check_call(['chrpath', '-l',", "to you under the Apache License, Version 2.0 (the # \"License\"); you may", "len(splits) > 1 else None if state == PARSING_NEW_RECORD: if key == KEY_CMD", "raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name():", "= get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib',", "else None if state == PARSING_NEW_RECORD: if key == KEY_CMD and val ==", "target_dst, config) def main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target", "relocatable and copy all of its dependencies into the artifact directory. \"\"\" if", "warning if no rpath is set on the binary. try: subprocess.check_call(['chrpath', '-l', target])", "logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root =", "err: logging.warning(\"No RPATH or RUNPATH set on target %s, continuing...\", target) return #", "the specified target. See man chrpath(1). \"\"\" # Continue with a warning if", "# Make sure we have the chrpath command available in the Linux build.", "python ################################################################################ # Licensed to the Apache Software Foundation (ASF) under one #", "to stderr and returns an empty map. \"\"\" resolved_paths = {} for raw_lib_path", "map of symbolic to resolved library dependencies of the given binary. See resolve_library_paths_macos().", "== LC_RPATH: if key == KEY_PATH: # Strip trailing metadata from rpath dump", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "routines that we assume may not be portable between macOS versions. # TODO(mpercy):", "not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR],", "lib_dst) # Change library search path or name for each archived library. modified_search_name", "of the executable referenced by 'target' from the build directory into the artifact", "dest): \"\"\" Copy the file with path 'src' to path 'dest'. If 'src'", "state == PARSING_RPATH and cmd_type == LC_RPATH: if key == KEY_PATH: # Strip", "os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break if not resolved: raise FileNotFoundError(\"Unable", "exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the", "rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config):", "\"\"\" Helper function that returns a list of rpaths parsed from the given", "= {} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue", "LC_RPATH: state = PARSING_RPATH continue if key == KEY_CMD and val == LC_LOAD_DYLIB:", "See man chrpath(1). \"\"\" # Continue with a warning if no rpath is", "are copied from the build # system and will not be updated if", "See the NOTICE file # distributed with this work for additional information #", "resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem", "copy all of its dependencies into the # artifact directory. return relocate_deps(target_src, target_dst,", "Add the build-support dir to the system path so we can import kudu-util.", "= re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break", "the # specific language governing permissions and limitations # under the License. ################################################################################", "See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in", "security dependencies are copied from the build # system and will not be", "target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target,", "the copied dependencies will be found when the executable is invoked. \"\"\" #", "Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE)", "# with the License. You may obtain a copy of the License at", "= re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want", "available on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable", "as a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the", "shared object library dependencies, with one shared object per entry. They are returned", "PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state", "optparse import os import os.path import re import shutil import subprocess import sys", "if key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function that", "key == KEY_PATH: # Strip trailing metadata from rpath dump line. values.append(val) if", "rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath", "from objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD =", "under one # or more contributor license agreements. See the NOTICE file #", "required by applicable law or agreed to in writing, # software distributed under", "If 'src' is a symlink, the link will be followed and 'dest' will", "in the Linux build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor = DependencyExtractor()", "for additional information # regarding copyright ownership. The ASF licenses this file #", "across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\",", "keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir'", "= 'name' KEY_PATH = 'path' # Exclude libraries that are GPL-licensed and libraries", "root to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their", "operating system on the runtime host is # patched. ################################################################################ import logging import", "returns a list of rpaths parsed from the given binary. \"\"\" dump =", "plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH or", "command', line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key =", "search path, with one search path per entry. * LC_LOAD_DYLIB: Returns a list", "be deployed to run an actual Kudu service, whether in production or #", "of rpaths parsed from the given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH,", "License for the # specific language governing permissions and limitations # under the", "(ASF) under one # or more contributor license agreements. See the NOTICE file", "the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst)", "following: * LC_RPATH: Returns a list containing the rpath search path, with one", "\"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\",", "software distributed under the License is distributed on an # \"AS IS\" BASIS,", "needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if", "thread # routines that we assume may not be portable between macOS versions.", "See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we have", "'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH = 'path'", "'$ORIGIN/../lib' # Make sure we have the chrpath command available in the Linux", "os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the file with path 'src' to", "for each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name,", "return # Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as", "return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all", "additional information # regarding copyright ownership. The ASF licenses this file # to", "libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst)", "# \"License\"); you may not use this file except in compliance # with", "that are not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc|", "build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\") config =", "no rpath is set on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError", "raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given binary. Returns", "OR CONDITIONS OF ANY # KIND, either express or implied. See the License", "and limitations # under the License. ################################################################################ # This script makes Kudu release", "= \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build", "directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make", "= raw_lib_path continue resolved = False for rpath in rpaths: resolved_path = re.sub('@rpath',", "% (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic", "dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an", "information. \"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT]", "return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir", "= DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for", "def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list of rpaths parsed from", "be properly resolved. $ORIGIN is always relative to the # running executable. chrpath(lib_dst,", "in compliance # with the License. You may obtain a copy of the", "implied. See the License for the # specific language governing permissions and limitations", "config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config", "all of its dependencies into the # artifact directory. return relocate_deps(target_src, target_dst, config)", "and thread # routines that we assume may not be portable between macOS", "== LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type ==", "command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given binary.", "False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst", "from get_rpaths_macos(). Returns a mapping from original to resolved library paths on success.", "command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given", "or RUNPATH set on target %s, continuing...\", target) return # Update the rpath.", "the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or", "needed. prep_artifact_dirs(config) # Copy the target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR],", "'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch)", "= artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def", "the rpath of the executable so that the copied dependencies will be found", "\"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a", "== LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper", "either express or implied. See the License for the # specific language governing", "object library dependencies, with one shared object per entry. They are returned as", "artifact_name) # Clear the artifact root to ensure a clean build. if os.path.exists(artifact_root):", "itself to look for its # dependencies in a relative location. chrpath(target_dst, NEW_RPATH)", "IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported", "'dest'. If 'src' is a symlink, the link will be followed and 'dest'", "raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break if not resolved:", "resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump)", "% (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:]", "\"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we have the chrpath command available", "rpath is set on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as", "any required artifact output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755)", "returns an empty map. \"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths: if", "for rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] =", "artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\"", "def relocate_target(target, config): \"\"\" Copy all dependencies of the executable referenced by 'target'", "libraries that are GPL-licensed and libraries that are not portable # across Linux", "never # be deployed to run an actual Kudu service, whether in production", "PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't", "dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See", "def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to resolved library dependencies of", "################################################################################ import logging import optparse import os import os.path import re import shutil", "config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root", "output per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError", "\"\"\" Run `objdump -p` on the given binary. Returns a list with one", "\"\"\" See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path)", "error to stderr and returns an empty map. \"\"\" resolved_paths = {} for", "\"linux\" elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4]", "raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for rpath", "line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1] if len(splits) > 1 else", "to chrpath for target %s\", target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\"", "LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type == LC_RPATH:", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else", "raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all dependencies of the executable", "mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src,", "line in dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits =", "chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs", "state == PARSING_NEW_RECORD: if key == KEY_CMD and val == LC_RPATH: state =", "relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all dependencies", "in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps().", "= os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to the system path so", "in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set", "directory, and change the rpath of the executable so that the copied dependencies", "Exclude libraries that are GPL-licensed and libraries that are not portable # across", "\"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any required", "PARSING_RPATH and cmd_type == LC_RPATH: if key == KEY_PATH: # Strip trailing metadata", "patched. ################################################################################ import logging import optparse import os import os.path import re import", "# Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath',", "len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1)", "License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "key = splits[0] val = splits[1] if len(splits) > 1 else None if", "GPL-licensed and libraries that are not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE", "the following: * LC_RPATH: Returns a list containing the rpath search path, with", "(sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging()", "stored in the MachO header, without being first resolved to an absolute path,", "not be portable between macOS versions. # TODO(mpercy): consider excluding libc++ as well.", "chrpath for target %s\", target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See", "executable referenced by 'target' from the build directory into the artifact directory, and", "a list of rpaths parsed from the given binary. \"\"\" dump = objdump_private_headers(binary_path)", "under the Apache License, Version 2.0 (the # \"License\"); you may not use", "into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src,", "import re import shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") #", "try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set", "subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set on target %s, continuing...\", target)", "return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\")", "artifact_root): \"\"\" Build a configuration map for convenient plumbing of path information. \"\"\"", "any libraries cannot be resolved, prints an error to stderr and returns an", "line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0]", "artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact root to", "open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version,", "may not be portable between macOS versions. # TODO(mpercy): consider excluding libc++ as", "= PARSING_RPATH continue if key == KEY_CMD and val == LC_LOAD_DYLIB: state =", "This script makes Kudu release binaries relocatable for easy use by # integration", "binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths =", "if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\"", "= get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact root to ensure", "per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as", "to find %s command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p`", "shared objects as well for transitive # dependencies to be properly resolved. $ORIGIN", "libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter out libs", "with an appropriate name. Including version, OS, and architecture. \"\"\" if IS_LINUX: os_str", "a list of shared object library dependencies, with one shared object per entry.", "Unless required by applicable law or agreed to in writing, # software distributed", "don't want to ship libSystem because it includes kernel and thread # routines", "distributed with this work for additional information # regarding copyright ownership. The ASF", "PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values = [] for", "val = splits[1] if len(splits) > 1 else None if state == PARSING_NEW_RECORD:", "\"Linux\" def check_for_command(command): \"\"\" Ensure that the specified command is available on the", "resolved_path) in libs.iteritems(): # Filter out libs we don't want to archive. if", "def relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable and copy all of", "continue if key == KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue", "copy_file(resolved_path, lib_dst) # Change library search path or name for each archived library.", "# KIND, either express or implied. See the License for the # specific", "= os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure", "to absolute filesystem paths using the rpath information returned from get_rpaths_macos(). Returns a", "to resolved library paths on success. If any libraries cannot be resolved, prints", "the executable so that the copied dependencies will be found when the executable", "relocatable and copy all of its dependencies into the # artifact directory. return", "a list containing the rpath search path, with one search path per entry.", "must be one of the following: * LC_RPATH: Returns a list containing the", "if state == PARSING_RPATH and cmd_type == LC_RPATH: if key == KEY_PATH: #", "IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\"", "from kudu_util import check_output, Colors, init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH", "def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute", "and copy all of its dependencies into the # artifact directory. return relocate_deps(target_src,", "location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\"", "<reponame>granthenke/kudu #!/usr/bin/env python ################################################################################ # Licensed to the Apache Software Foundation (ASF) under", "dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD =", "versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We", "if re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2)", "path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\"", "not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for rpath in rpaths:", "path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors,", "raw_lib_path continue resolved = False for rpath in rpaths: resolved_path = re.sub('@rpath', rpath,", "\"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err)", "logging.error(\"Unable to find %s command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump", "so that the copied dependencies will be found when the executable is invoked.", "from the build # system and will not be updated if the operating", "# integration tests using a mini cluster. The resulting binaries should never #", "'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] ==", "be resolved, prints an error to stderr and returns an empty map. \"\"\"", "config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root,", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function", "ship libSystem because it includes kernel and thread # routines that we assume", "artifact output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not", "except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set on target %s, continuing...\",", "os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\"", "check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def", "system and will not be updated if the operating system on the runtime", "if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]):", "target relocatable and copy all of its dependencies into the # artifact directory.", "# We have to set the RUNPATH of the shared objects as well", "try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return []", "= parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\"", "PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR],", "RUNPATH for the specified target. See man chrpath(1). \"\"\" # Continue with a", "output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]):", "Copy all dependencies of the executable referenced by 'target' from the build directory", "library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify", "using the rpath information returned from get_rpaths_macos(). Returns a mapping from original to", "all security dependencies are copied from the build # system and will not", "resulting binaries should never # be deployed to run an actual Kudu service,", "= \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r')", "into the # artifact directory. return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv)", "LC_RPATH: if key == KEY_PATH: # Strip trailing metadata from rpath dump line.", "for (search_name, resolved_path) in libs.iteritems(): # Filter out libs we don't want to", "list containing the rpath search path, with one search path per entry. *", "OF ANY # KIND, either express or implied. See the License for the", "tests using a mini cluster. The resulting binaries should never # be deployed", "the RPATH or RUNPATH for the specified target. See man chrpath(1). \"\"\" #", "that are GPL-licensed and libraries that are not portable # across Linux kernel", "target_dst, config): \"\"\" Make the target relocatable and copy all of its dependencies", "# Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root):", "= 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def", "name. Including version, OS, and architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif", "= re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the rpath.", "to resolved library dependencies of the given binary. See resolve_library_paths_macos(). \"\"\" dump =", "find %s command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on", "an actual Kudu service, whether in production or # development, because all security", "import os import os.path import re import shutil import subprocess import sys SOURCE_ROOT", "== \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that the", "output from objdump_private_headers() for macOS. 'cmd_type' must be one of the following: *", "init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1) artifact_name", "all of its dependencies into the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src,", "rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the", "raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False", "rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool',", "the License. You may obtain a copy of the License at # #", "Build a configuration map for convenient plumbing of path information. \"\"\" config =", "its dependencies into the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config)", "dependencies into the # artifact directory. return relocate_deps(target_src, target_dst, config) def main(): if", "directory %s does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root,", "agreements. See the NOTICE file # distributed with this work for additional information", "# We must also update the RUNPATH of the executable itself to look", "the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the rpath", "the target relocatable and copy all of its dependencies into the artifact directory.", "config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config):", "build-support dir to the system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\"))", "target %s\", target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux", "binaries should never # be deployed to run an actual Kudu service, whether", "'-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target %s\",", "# across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.*", "file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH", "from the given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths,", "targets and their dependencies in archive...\") config = mkconfig(build_root, artifact_root) for target in", "their dependencies in archive...\") config = mkconfig(build_root, artifact_root) for target in targets: relocate_target(target,", "dependencies into the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if", "splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1] if len(splits)", "See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH,", "KEY_PATH: # Strip trailing metadata from rpath dump line. values.append(val) if state ==", "# Add the build-support dir to the system path so we can import", "resolved = False for rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if", "output from objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD", "'cmd_type' must be one of the following: * LC_RPATH: Returns a list containing", "= os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root,", "system on the runtime host is # patched. ################################################################################ import logging import optparse", "os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any", "= os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target relocatable and copy all", "= re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT =", "limitations # under the License. ################################################################################ # This script makes Kudu release binaries", "portable between macOS versions. # TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE =", "executable so that the copied dependencies will be found when the executable is", "target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool',", "= os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name =", "that returns a list of rpaths parsed from the given binary. \"\"\" dump", "dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"),", "KEY_CMD and val == LC_RPATH: state = PARSING_RPATH continue if key == KEY_CMD", "prep_artifact_dirs(config): \"\"\" Create any required artifact output directories, if needed. \"\"\" if not", "except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target %s\", target) raise err", "by 'target' from the build directory into the artifact directory, and change the", "as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the", "logging.warning(\"Failed to chrpath for target %s\", target) raise err def relocate_deps_linux(target_src, target_dst, config):", "command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\", command) raise err", "ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\"", "implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter", "configuration map for convenient plumbing of path information. \"\"\" config = {} config[BUILD_ROOT]", "an empty map. \"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths: if not", "try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\", command)", "target) return # Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError", "'name' KEY_PATH = 'path' # Exclude libraries that are GPL-licensed and libraries that", "in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a", "of the following: * LC_RPATH: Returns a list containing the rpath search path,", "get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to resolved library dependencies of the", "to in writing, # software distributed under the License is distributed on an", "and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path):", "\"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as", "dependencies of the given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths =", "to run an actual Kudu service, whether in production or # development, because", "rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved =", "and val == LC_RPATH: state = PARSING_RPATH continue if key == KEY_CMD and", "[] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers() for", "man chrpath(1). \"\"\" # Continue with a warning if no rpath is set", "resolved: raise FileNotFoundError(\"Unable to locate library %s in rpath %s\" % (raw_lib_path, rpaths))", "resolved_paths = {} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path", "LC_RPATH: Returns a list containing the rpath search path, with one search path", "script makes Kudu release binaries relocatable for easy use by # integration tests", "and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state == PARSING_RPATH and", "# This script makes Kudu release binaries relocatable for easy use by #", "resolved, prints an error to stderr and returns an empty map. \"\"\" resolved_paths", "'-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable and", "is a symlink, the link will be followed and 'dest' will be written", "the # artifact directory. return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) <", "continue # Archive the rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path))", "PARSING_NEW_RECORD: if key == KEY_CMD and val == LC_RPATH: state = PARSING_RPATH continue", "kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging from dep_extract import DependencyExtractor", "subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\", command) raise err def objdump_private_headers(binary_path):", "resolved = True break if not resolved: raise FileNotFoundError(\"Unable to locate library %s", "symbolic to resolved library dependencies of the given binary. See resolve_library_paths_macos(). \"\"\" dump", ")) sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if", "Change library search path or name for each archived library. modified_search_name = re.sub('^.*/',", "target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for", "relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' #", "followed and 'dest' will be written as a plain file. \"\"\" shutil.copyfile(src, dest)", "the NOTICE file # distributed with this work for additional information # regarding", "in writing, # software distributed under the License is distributed on an #", "the Apache Software Foundation (ASF) under one # or more contributor license agreements.", "import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd'", "target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the", "as well for transitive # dependencies to be properly resolved. $ORIGIN is always", "well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir'", "into the artifact directory, and change the rpath of the executable so that", "is always relative to the # running executable. chrpath(lib_dst, NEW_RPATH) # We must", "Ensure that the specified command is available on the PATH. \"\"\" try: subprocess.check_call(['which',", "available in the Linux build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor =", "of path information. \"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root,", "Run `objdump -p` on the given binary. Returns a list with one line", "not resolved: raise FileNotFoundError(\"Unable to locate library %s in rpath %s\" % (raw_lib_path,", "target relocatable and copy all of its dependencies into the artifact directory. \"\"\"", "target) copy_file(target_src, target_dst) # Make the target relocatable and copy all of its", "path or name for each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool',", "the # running executable. chrpath(lib_dst, NEW_RPATH) # We must also update the RUNPATH", "os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set the RUNPATH of the", "-p` on the given binary. Returns a list with one line of objdump", "NEW_RPATH = '$ORIGIN/../lib' # Make sure we have the chrpath command available in", "directory into the artifact directory, and change the rpath of the executable so", "relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def", "its dependencies into the # artifact directory. return relocate_deps(target_src, target_dst, config) def main():", "\"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return", "library %s in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\"", "if the operating system on the runtime host is # patched. ################################################################################ import", "ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in", "to locate library %s in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def", "'path' # Exclude libraries that are GPL-licensed and libraries that are not portable", "OS, and architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str =", "RUNPATH set on target %s, continuing...\", target) return # Update the rpath. try:", "err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH =", "artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config):", "< 3: print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1) #", "whether in production or # development, because all security dependencies are copied from", "applicable law or agreed to in writing, # software distributed under the License", "Parses the output from objdump_private_headers() for macOS. 'cmd_type' must be one of the", "NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs =", "the rpath search path, with one search path per entry. * LC_LOAD_DYLIB: Returns", "the output from objdump_private_headers() for macOS. 'cmd_type' must be one of the following:", "filesystem paths using the rpath information returned from get_rpaths_macos(). Returns a mapping from", "from original to resolved library paths on success. If any libraries cannot be", "if no rpath is set on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except", "2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values = [] for line in", "# Make the target relocatable and copy all of its dependencies into the", "os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "# development, because all security dependencies are copied from the build # system", "state = PARSING_NONE values = [] for line in dump: if re.match('^Load command',", "search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src)", "config def prep_artifact_dirs(config): \"\"\" Create any required artifact output directories, if needed. \"\"\"", "# dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\"", "like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\" # Parsing state enum", "rpath of the executable so that the copied dependencies will be found when", "def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for convenient plumbing of path", "= 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0]", "binaries relocatable for easy use by # integration tests using a mini cluster.", "sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging from dep_extract import DependencyExtractor #", "target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable and copy all", "# Create artifact directories, if needed. prep_artifact_dirs(config) # Copy the target into the", "resolved_path resolved = True break if not resolved: raise FileNotFoundError(\"Unable to locate library", "the chrpath command available in the Linux build. check_for_command('chrpath') # Copy the linked", "except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s command\", command) raise err def", "\"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] =", "also update the RUNPATH of the executable itself to look for its #", "its # dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config):", "binary. Returns a list with one line of objdump output per record. \"\"\"", "modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the", "[target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets", "and cmd_type == LC_RPATH: if key == KEY_PATH: # Strip trailing metadata from", "production or # development, because all security dependencies are copied from the build", "into the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS:", "if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break if not resolved: raise", "the RUNPATH of the executable itself to look for its # dependencies in", "if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the file with", "None if state == PARSING_NEW_RECORD: if key == KEY_CMD and val == LC_RPATH:", "raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH", "Apache Software Foundation (ASF) under one # or more contributor license agreements. See", "err: logging.error(\"Unable to find %s command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run", "except subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\"", "os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any required artifact output directories,", "specified target. See man chrpath(1). \"\"\" # Continue with a warning if no", "the rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) #", "not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name()", "mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the file", "copied from the build # system and will not be updated if the", "...) to absolute filesystem paths using the rpath information returned from get_rpaths_macos(). Returns", "success. If any libraries cannot be resolved, prints an error to stderr and", "config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] =", "copied dependencies will be found when the executable is invoked. \"\"\" # Create", "\"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the", "We don't want to ship libSystem because it includes kernel and thread #", "NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version =", "import logging import optparse import os import os.path import re import shutil import", "= os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any required artifact output", "search path per entry. * LC_LOAD_DYLIB: Returns a list of shared object library", "resolved. $ORIGIN is always relative to the # running executable. chrpath(lib_dst, NEW_RPATH) #", "path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs:", "directory. return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) < 3: print(\"Usage: %s", "\"\"\" Returns a map of symbolic to resolved library dependencies of the given", "required artifact output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if", "check_output, Colors, init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB", "config): \"\"\" Make the target relocatable and copy all of its dependencies into", "for easy use by # integration tests using a mini cluster. The resulting", "= os.path.join(build_root, artifact_name) # Clear the artifact root to ensure a clean build.", "os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for", "first resolved to an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the", "dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src)", "build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact", "dir to the system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from", "subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths = get_rpaths_macos(target_src) for", "using a mini cluster. The resulting binaries should never # be deployed to", "chrpath(1). \"\"\" # Continue with a warning if no rpath is set on", "val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type", "more contributor license agreements. See the NOTICE file # distributed with this work", "try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for", "subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target", "os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that", "version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name def", "a list with one line of objdump output per record. \"\"\" check_for_command('objdump') try:", "\"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we", "build_root = sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s", "\"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str,", "not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt|", "CONDITIONS OF ANY # KIND, either express or implied. See the License for", "Returns a list containing the rpath search path, with one search path per", "Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR =", "= 3 state = PARSING_NONE values = [] for line in dump: if", "= os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that the specified command is", "as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return", "get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list of rpaths parsed from the", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir", "continue resolved = False for rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path)", "express or implied. See the License for the # specific language governing permissions", "or RUNPATH for the specified target. See man chrpath(1). \"\"\" # Continue with", "being first resolved to an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump'", "build directory into the artifact directory, and change the rpath of the executable", "Create any required artifact output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT],", "object per entry. They are returned as stored in the MachO header, without", "copy all of its dependencies into the artifact directory. \"\"\" if IS_LINUX: return", "rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath',", "rpath search path, with one search path per entry. * LC_LOAD_DYLIB: Returns a", "################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or", "given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\"", "'@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable and copy", "import os.path import re import shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__),", "with one search path per entry. * LC_LOAD_DYLIB: Returns a list of shared", "KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "# Filter out libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue #", "True break if not resolved: raise FileNotFoundError(\"Unable to locate library %s in rpath", "line of objdump output per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\",", "dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path or", "absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers().", "Copy the target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst =", "distributed under the License is distributed on an # \"AS IS\" BASIS, WITHOUT", "FileNotFoundError(\"Unable to locate library %s in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths", "rpath information returned from get_rpaths_macos(). Returns a mapping from original to resolved library", "0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE", "== PARSING_NEW_RECORD: if key == KEY_CMD and val == LC_RPATH: state = PARSING_RPATH", "Create an archive with an appropriate name. Including version, OS, and architecture. \"\"\"", "= sys.argv[1] targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does", "map for convenient plumbing of path information. \"\"\" config = {} config[BUILD_ROOT] =", "link will be followed and 'dest' will be written as a plain file.", "actual Kudu service, whether in production or # development, because all security dependencies", "os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target relocatable", "%s, continuing...\", target) return # Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target])", "KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state == PARSING_RPATH", "and copy all of its dependencies into the artifact directory. \"\"\" if IS_LINUX:", "to look for its # dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def", "`objdump -p` on the given binary. Returns a list with one line of", "want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the runtime", "that the specified command is available on the PATH. \"\"\" try: subprocess.check_call(['which', command])", "and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\" #", "shared object per entry. They are returned as stored in the MachO header,", "PARSING_RPATH continue if key == KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS", "Returns a map of symbolic to resolved library dependencies of the given binary.", "invoked. \"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config) # Copy the target", "an archive with an appropriate name. Including version, OS, and architecture. \"\"\" if", "Archive the rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst)", "convenient plumbing of path information. \"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR]", "%s kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return", "#!/usr/bin/env python ################################################################################ # Licensed to the Apache Software Foundation (ASF) under one", "the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search", "not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear", "values = [] for line in dump: if re.match('^Load command', line): state =", "on target %s, continuing...\", target) return # Update the rpath. try: subprocess.check_call(['chrpath', '-r',", "state = PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val", "def get_artifact_name(): \"\"\" Create an archive with an appropriate name. Including version, OS,", "os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755)", "development, because all security dependencies are copied from the build # system and", "key == KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns", "be found when the executable is invoked. \"\"\" # Create artifact directories, if", "3 state = PARSING_NONE values = [] for line in dump: if re.match('^Load", "copy_file(lib_src, lib_dst) # We have to set the RUNPATH of the shared objects", "is available on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err:", "os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the file with path 'src'", "IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that the specified command", "of its dependencies into the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst,", "if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for rpath in", ")\\.so\"\"\", re.VERBOSE) # We don't want to ship libSystem because it includes kernel", "print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments.", "Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2", "PARSING_LIB_PATHS = 3 state = PARSING_NONE values = [] for line in dump:", "lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path or name", "if key == KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if", "= PARSING_NONE values = [] for line in dump: if re.match('^Load command', line):", "{} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved", "# Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH =", "logging import optparse import os import os.path import re import shutil import subprocess", "'@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) # Modify the rpath. rpaths =", "on success. If any libraries cannot be resolved, prints an error to stderr", "sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to the system", "resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to resolved library dependencies", "for its # dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst,", "objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def", "Linux build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path:", "sure we have the chrpath command available in the Linux build. check_for_command('chrpath') #", "kudu_util import check_output, Colors, init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH =", "we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging from", "'-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set on target", "KEY_PATH = 'path' # Exclude libraries that are GPL-licensed and libraries that are", "given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths", "os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target relocatable and copy all of", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "> 1 else None if state == PARSING_NEW_RECORD: if key == KEY_CMD and", "resolved library dependencies of the given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path)", "config = mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config) if __name__ ==", "True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src,", "the License. ################################################################################ # This script makes Kudu release binaries relocatable for easy", "SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to the system path", "directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst,", "libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR", "an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from", "NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy all dependencies of the executable referenced", "resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive with an appropriate name. Including", "this file # to you under the Apache License, Version 2.0 (the #", "# specific language governing permissions and limitations # under the License. ################################################################################ #", "PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values def", "per entry. They are returned as stored in the MachO header, without being", "the link will be followed and 'dest' will be written as a plain", "= 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH =", "Version 2.0 (the # \"License\"); you may not use this file except in", "state = PARSING_RPATH continue if key == KEY_CMD and val == LC_LOAD_DYLIB: state", "target. See man chrpath(1). \"\"\" # Continue with a warning if no rpath", "target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target relocatable and", "libSystem because it includes kernel and thread # routines that we assume may", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied.", "a mini cluster. The resulting binaries should never # be deployed to run", "the given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths):", "values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list of", "have to set the RUNPATH of the shared objects as well for transitive", "if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755)", "have the chrpath command available in the Linux build. check_for_command('chrpath') # Copy the", "Filter out libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive", "We must also update the RUNPATH of the executable itself to look for", "Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the", "of its dependencies into the # artifact directory. return relocate_deps(target_src, target_dst, config) def", "= build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\")", "search path or name for each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name)", "PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to find %s", "chrpath(lib_dst, NEW_RPATH) # We must also update the RUNPATH of the executable itself", "runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path", "== PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val) return values", "and their dependencies in archive...\") config = mkconfig(build_root, artifact_root) for target in targets:", "the executable itself to look for its # dependencies in a relative location.", "integration tests using a mini cluster. The resulting binaries should never # be", "running executable. chrpath(lib_dst, NEW_RPATH) # We must also update the RUNPATH of the", "cmd_type == LC_RPATH: if key == KEY_PATH: # Strip trailing metadata from rpath", "ASF licenses this file # to you under the Apache License, Version 2.0", "assume may not be portable between macOS versions. # TODO(mpercy): consider excluding libc++", "'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir'", "excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root'", "library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the rpath information", "# distributed with this work for additional information # regarding copyright ownership. The", "referenced by 'target' from the build directory into the artifact directory, and change", "archive...\") config = mkconfig(build_root, artifact_root) for target in targets: relocate_target(target, config) if __name__", "command available in the Linux build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor", "= 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR =", "shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support", "the shared objects as well for transitive # dependencies to be properly resolved.", "with this work for additional information # regarding copyright ownership. The ASF licenses", "val == LC_RPATH: state = PARSING_RPATH continue if key == KEY_CMD and val", "# Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR", "binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump):", "the Linux build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda", "written as a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change", "\"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH for", "subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH set on", "if not resolved: raise FileNotFoundError(\"Unable to locate library %s in rpath %s\" %", "writing, # software distributed under the License is distributed on an # \"AS", "of the executable itself to look for its # dependencies in a relative", "as err: logging.warning(\"Failed to chrpath for target %s\", target) raise err def relocate_deps_linux(target_src,", "out libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the", "resolved library paths on success. If any libraries cannot be resolved, prints an", "build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR]", "\"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return relocate_deps_macos(target_src, target_dst, config)", "dependencies, with one shared object per entry. They are returned as stored in", "return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive with an appropriate name.", "from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the rpath information returned from", "sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact root", "# We don't want to ship libSystem because it includes kernel and thread", "deployed to run an actual Kudu service, whether in production or # development,", "== LC_RPATH: state = PARSING_RPATH continue if key == KEY_CMD and val ==", "Clear the artifact root to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including", "values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list of rpaths parsed", "prep_artifact_dirs(config) # Copy the target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target)", "get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter out libs we don't", "of the given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB,", "os import os.path import re import shutil import subprocess import sys SOURCE_ROOT =", "directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]): os.makedirs(config[ARTIFACT_ROOT], mode=0755) if not os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR],", "The ASF licenses this file # to you under the Apache License, Version", "properly resolved. $ORIGIN is always relative to the # running executable. chrpath(lib_dst, NEW_RPATH)", "platform\") def relocate_target(target, config): \"\"\" Copy all dependencies of the executable referenced by", "file # to you under the Apache License, Version 2.0 (the # \"License\");", "= dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) #", "specified command is available on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError", "target_dst) # Make the target relocatable and copy all of its dependencies into", "= os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set the RUNPATH of", "logging.warning(\"No RPATH or RUNPATH set on target %s, continuing...\", target) return # Update", "\"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter out", "cannot be resolved, prints an error to stderr and returns an empty map.", "= 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values =", "per entry. * LC_LOAD_DYLIB: Returns a list of shared object library dependencies, with", "if state == PARSING_NEW_RECORD: if key == KEY_CMD and val == LC_RPATH: state", "rpaths) def get_artifact_name(): \"\"\" Create an archive with an appropriate name. Including version,", "# software distributed under the License is distributed on an # \"AS IS\"", "host is # patched. ################################################################################ import logging import optparse import os import os.path", "resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True", "state = PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type == LC_RPATH: if", "Make the target relocatable and copy all of its dependencies into the #", "is invoked. \"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config) # Copy the", "on the given binary. Returns a list with one line of objdump output", "dump line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key", "not be updated if the operating system on the runtime host is #", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "locate library %s in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path):", "= 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state =", "PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR],", "else True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src))", "on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH", "the rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst])", "# Change library search path or name for each archived library. modified_search_name =", "\"\"\" Copy the file with path 'src' to path 'dest'. If 'src' is", "in libs.iteritems(): # Filter out libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR", "config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\"", "# under the License. ################################################################################ # This script makes Kudu release binaries relocatable", "config): \"\"\" Copy all dependencies of the executable referenced by 'target' from the", "archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change', search_name, modified_search_name, target_dst]) #", "= os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target", "use this file except in compliance # with the License. You may obtain", "\"\"\" Change the RPATH or RUNPATH for the specified target. See man chrpath(1).", "\"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command): \"\"\" Ensure that the specified", "if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst =", "with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" %", "# dependencies to be properly resolved. $ORIGIN is always relative to the #", "trailing metadata from rpath dump line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type", "'src' to path 'dest'. If 'src' is a symlink, the link will be", "for target %s\", target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps().", "'artifact_root' ARTIFACT_BIN_DIR = 'artifact_bin_dir' ARTIFACT_LIB_DIR = 'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX", "dump): \"\"\" Parses the output from objdump_private_headers() for macOS. 'cmd_type' must be one", "@rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\" # Parsing state enum values.", "os.path import re import shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\")", "\"\"\" Build a configuration map for convenient plumbing of path information. \"\"\" config", "= sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root)", "record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\", \"-p\", binary_path]) except subprocess.CalledProcessError as err:", "objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1", "PARSING_LIB_PATHS continue if state == PARSING_RPATH and cmd_type == LC_RPATH: if key ==", "dependencies will be found when the executable is invoked. \"\"\" # Create artifact", "path per entry. * LC_LOAD_DYLIB: Returns a list of shared object library dependencies,", "release binaries relocatable for easy use by # integration tests using a mini", "always relative to the # running executable. chrpath(lib_dst, NEW_RPATH) # We must also", "\"\"\" Copy all dependencies of the executable referenced by 'target' from the build", "a symlink, the link will be followed and 'dest' will be written as", "for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved =", "list with one line of objdump output per record. \"\"\" check_for_command('objdump') try: output", "continue if state == PARSING_RPATH and cmd_type == LC_RPATH: if key == KEY_PATH:", "import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging from dep_extract import", "splits[0] val = splits[1] if len(splits) > 1 else None if state ==", "artifact directories, if needed. prep_artifact_dirs(config) # Copy the target into the artifact directory.", "# to you under the Apache License, Version 2.0 (the # \"License\"); you", "Helper function that returns a list of rpaths parsed from the given binary.", "values.append(val) if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME:", "by applicable law or agreed to in writing, # software distributed under the", "one search path per entry. * LC_LOAD_DYLIB: Returns a list of shared object", "config) def main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target ...]\"", "on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except subprocess.CalledProcessError as err: logging.error(\"Unable to", "dep_extractor.extract_deps(target_src) for lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We", "build # system and will not be updated if the operating system on", "the License for the # specific language governing permissions and limitations # under", "'dest' will be written as a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target,", "one line of objdump output per record. \"\"\" check_for_command('objdump') try: output = check_output([\"objdump\",", "os_str = \"linux\" elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch", "dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library", "artifact_root = os.path.join(build_root, artifact_name) # Clear the artifact root to ensure a clean", "* LC_LOAD_DYLIB: Returns a list of shared object library dependencies, with one shared", "map. \"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path]", "LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH = 'path' #", "set on target %s, continuing...\", target) return # Update the rpath. try: subprocess.check_call(['chrpath',", "= '$ORIGIN/../lib' # Make sure we have the chrpath command available in the", "= resolved_path resolved = True break if not resolved: raise FileNotFoundError(\"Unable to locate", "and libraries that are not portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE =", "key == KEY_CMD and val == LC_RPATH: state = PARSING_RPATH continue if key", "shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\") config = mkconfig(build_root, artifact_root) for", "\"\"\" Ensure that the specified command is available on the PATH. \"\"\" try:", "subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses", "to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies", "# be deployed to run an actual Kudu service, whether in production or", "artifact root to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and", "continuing...\", target) return # Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except", "chrpath command available in the Linux build. check_for_command('chrpath') # Copy the linked libraries.", "logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from", "under the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "libraries cannot be resolved, prints an error to stderr and returns an empty", "with one shared object per entry. They are returned as stored in the", "(version, os_str, arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map", "\"../..\") # Add the build-support dir to the system path so we can", "empty map. \"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"):", "Licensed to the Apache Software Foundation (ASF) under one # or more contributor", "or more contributor license agreements. See the NOTICE file # distributed with this", "Foundation (ASF) under one # or more contributor license agreements. See the NOTICE", "to the # running executable. chrpath(lib_dst, NEW_RPATH) # We must also update the", "a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH", "and architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str = \"osx\"", "or agreed to in writing, # software distributed under the License is distributed", "governing permissions and limitations # under the License. ################################################################################ # This script makes", "libs we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest", "os.path.join(build_root, artifact_name) # Clear the artifact root to ensure a clean build. if", "= True break if not resolved: raise FileNotFoundError(\"Unable to locate library %s in", "return values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a list of rpaths", "platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\")", "rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path", "PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3 state = PARSING_NONE values", "\"License\"); you may not use this file except in compliance # with the", "def copy_file(src, dest): \"\"\" Copy the file with path 'src' to path 'dest'.", "NEW_RPATH) # We must also update the RUNPATH of the executable itself to", "RUNPATH of the executable itself to look for its # dependencies in a", "\"\"\" Create an archive with an appropriate name. Including version, OS, and architecture.", "'-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\" Make", "check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter out libs we don't want", "== KEY_NAME: values.append(val) return values def get_rpaths_macos(binary_path): \"\"\" Helper function that returns a", "mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for convenient plumbing of path information.", "the artifact directory, and change the rpath of the executable so that the", "IS_MACOS: return relocate_deps_macos(target_src, target_dst, config) raise NotImplementedError(\"Unsupported platform\") def relocate_target(target, config): \"\"\" Copy", "change the rpath of the executable so that the copied dependencies will be", "not use this file except in compliance # with the License. You may", "without being first resolved to an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo", "os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to the system path so we", "re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break if", "libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to ship libSystem", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool')", "if len(splits) > 1 else None if state == PARSING_NEW_RECORD: if key ==", "shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH for the", "def chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH for the specified target.", "= False for rpath in rpaths: resolved_path = re.sub('@rpath', rpath, raw_lib_path) if os.path.exists(resolved_path):", "artifact directory. return relocate_deps(target_src, target_dst, config) def main(): if len(sys.argv) < 3: print(\"Usage:", "that the copied dependencies will be found when the executable is invoked. \"\"\"", "if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0], ))", "paths on success. If any libraries cannot be resolved, prints an error to", "$ORIGIN is always relative to the # running executable. chrpath(lib_dst, NEW_RPATH) # We", "\"\"\" # Parsing state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH", "\"\"\" Create any required artifact output directories, if needed. \"\"\" if not os.path.exists(config[ARTIFACT_ROOT]):", "libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to ship libSystem because it includes", "the build # system and will not be updated if the operating system", "import optparse import os import os.path import re import shutil import subprocess import", "def main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target ...]\" %", "look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\" # Parsing state", "If any libraries cannot be resolved, prints an error to stderr and returns", "'cmd' KEY_NAME = 'name' KEY_PATH = 'path' # Exclude libraries that are GPL-licensed", "Modify the rpath. rpaths = get_rpaths_macos(target_src) for rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath,", "subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst, config): \"\"\"", "LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH", "work for additional information # regarding copyright ownership. The ASF licenses this file", "os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path or name for each archived", "target %s, continuing...\", target) return # Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath,", "archive with an appropriate name. Including version, OS, and architecture. \"\"\" if IS_LINUX:", "be one of the following: * LC_RPATH: Returns a list containing the rpath", "are GPL-licensed and libraries that are not portable # across Linux kernel versions.", "target) raise err def relocate_deps_linux(target_src, target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\"", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS", "err: logging.warning(\"Failed to chrpath for target %s\", target) raise err def relocate_deps_linux(target_src, target_dst,", "or # development, because all security dependencies are copied from the build #", "you under the Apache License, Version 2.0 (the # \"License\"); you may not", "artifact directory, and change the rpath of the executable so that the copied", "objects as well for transitive # dependencies to be properly resolved. $ORIGIN is", "rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to resolved", "objdump_private_headers() for macOS. 'cmd_type' must be one of the following: * LC_RPATH: Returns", "mode=0755) def copy_file(src, dest): \"\"\" Copy the file with path 'src' to path", "must also update the RUNPATH of the executable itself to look for its", "RPATH or RUNPATH for the specified target. See man chrpath(1). \"\"\" # Continue", "dependencies of the executable referenced by 'target' from the build directory into the", "check_for_command('chrpath') # Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if", "key == KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state", "to be properly resolved. $ORIGIN is always relative to the # running executable.", "relative to the # running executable. chrpath(lib_dst, NEW_RPATH) # We must also update", "License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version = version.readline().strip().decode(\"utf-8\") artifact_name", "= [] for line in dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD", "paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using the rpath information returned", "IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT,", "Update the rpath. try: subprocess.check_call(['chrpath', '-r', new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed", "because all security dependencies are copied from the build # system and will", "the build-support dir to the system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT,", "returned from get_rpaths_macos(). Returns a mapping from original to resolved library paths on", "in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src, target_dst,", "chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH for the specified target. See", "the given binary. Returns a list with one line of objdump output per", "target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target %s\", target) raise", "the specified command is available on the PATH. \"\"\" try: subprocess.check_call(['which', command]) except", "as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR =", "Returns a list with one line of objdump output per record. \"\"\" check_for_command('objdump')", "'artifact_lib_dir' IS_MACOS = os.uname()[0] == \"Darwin\" IS_LINUX = os.uname()[0] == \"Linux\" def check_for_command(command):", "'src' is a symlink, the link will be followed and 'dest' will be", "we don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of", "header, without being first resolved to an absolute path, and may look like:", "libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs =", "os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to set the RUNPATH of the shared", "resolved to an absolute path, and may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the", "for macOS. 'cmd_type' must be one of the following: * LC_RPATH: Returns a", "parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...)", "entry. They are returned as stored in the MachO header, without being first", "...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root = sys.argv[1] targets =", "regarding copyright ownership. The ASF licenses this file # to you under the", "to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the runtime dependencies.", "raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"), 'r') as version: version", "IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\")", "from the build directory into the artifact directory, and change the rpath of", "this work for additional information # regarding copyright ownership. The ASF licenses this", "ANY # KIND, either express or implied. See the License for the #", "contributor license agreements. See the NOTICE file # distributed with this work for", "dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive with an appropriate", "rpaths parsed from the given binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump)", "directories, if needed. prep_artifact_dirs(config) # Copy the target into the artifact directory. target_src", "parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create", "# system and will not be updated if the operating system on the", "as err: logging.warning(\"No RPATH or RUNPATH set on target %s, continuing...\", target) return", "plumbing of path information. \"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] =", "# Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path)", "See the License for the # specific language governing permissions and limitations #", "re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1] if len(splits) > 1", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "Make the target relocatable and copy all of its dependencies into the artifact", "Returns a list of shared object library dependencies, with one shared object per", "targets = sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\",", "archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the runtime dependencies. lib_dst", "architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS: os_str = \"osx\" else:", "KIND, either express or implied. See the License for the # specific language", "easy use by # integration tests using a mini cluster. The resulting binaries", "macOS. 'cmd_type' must be one of the following: * LC_RPATH: Returns a list", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "permissions and limitations # under the License. ################################################################################ # This script makes Kudu", "resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for rpath in rpaths: resolved_path =", "relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure we have the", "= re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1] if len(splits) >", "compliance # with the License. You may obtain a copy of the License", "binary. \"\"\" dump = objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve", "new_rpath, target]) except subprocess.CalledProcessError as err: logging.warning(\"Failed to chrpath for target %s\", target)", "of the executable so that the copied dependencies will be found when the", "1 else None if state == PARSING_NEW_RECORD: if key == KEY_CMD and val", "with the License. You may obtain a copy of the License at #", "== KEY_CMD and val == LC_LOAD_DYLIB: state = PARSING_LIB_PATHS continue if state ==", "the output from objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE = 0", "a mapping from original to resolved library paths on success. If any libraries", "if key == KEY_PATH: # Strip trailing metadata from rpath dump line. values.append(val)", "%s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of", "except in compliance # with the License. You may obtain a copy of", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "you may not use this file except in compliance # with the License.", "be updated if the operating system on the runtime host is # patched.", "= 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH = 'path' # Exclude", "dump = objdump_private_headers(binary_path) raw_library_paths = parse_objdump_macos(LC_LOAD_DYLIB, dump) rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths,", "# patched. ################################################################################ import logging import optparse import os import os.path import re", "librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) # We don't want to ship libSystem because", "the MachO header, without being first resolved to an absolute path, and may", "re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT = 'artifact_root'", "the system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import", "= splits[0] val = splits[1] if len(splits) > 1 else None if state", "return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for convenient plumbing", "build. check_for_command('chrpath') # Copy the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False", "for transitive # dependencies to be properly resolved. $ORIGIN is always relative to", "line. values.append(val) if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key ==", "They are returned as stored in the MachO header, without being first resolved", "enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS =", "the artifact directory. \"\"\" if IS_LINUX: return relocate_deps_linux(target_src, target_dst, config) if IS_MACOS: return", "consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT =", "DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB = 'LC_LOAD_DYLIB' KEY_CMD = 'cmd' KEY_NAME", "== KEY_CMD and val == LC_RPATH: state = PARSING_RPATH continue if key ==", "rpath, raw_lib_path) if os.path.exists(resolved_path): resolved_paths[raw_lib_path] = resolved_path resolved = True break if not", "library dependencies, with one shared object per entry. They are returned as stored", "= parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive with", "%s does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name)", "values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS = 3", "and 'dest' will be written as a plain file. \"\"\" shutil.copyfile(src, dest) def", "= 'path' # Exclude libraries that are GPL-licensed and libraries that are not", "PAT_MACOS_LIB_EXCLUDE = re.compile(r\"libSystem\") # Config keys. BUILD_ROOT = 'build_root' BUILD_BIN_DIR = 'build_bin_dir' ARTIFACT_ROOT", "return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers() for macOS.", "Colors, init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH' LC_LOAD_DYLIB =", "################################################################################ # This script makes Kudu release binaries relocatable for easy use by", "License, Version 2.0 (the # \"License\"); you may not use this file except", "raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for rpath in rpaths: resolved_path", "this file except in compliance # with the License. You may obtain a", "config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make sure", "logging.info(\"Including targets and their dependencies in archive...\") config = mkconfig(build_root, artifact_root) for target", "# Copy the target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst", "rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map", "be written as a plain file. \"\"\" shutil.copyfile(src, dest) def chrpath(target, new_rpath): \"\"\"", "does not exist\", build_root) sys.exit(1) artifact_name = get_artifact_name() artifact_root = os.path.join(build_root, artifact_name) #", "License. ################################################################################ # This script makes Kudu release binaries relocatable for easy use", "file with path 'src' to path 'dest'. If 'src' is a symlink, the", "lib_src in libs: lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(lib_src)) copy_file(lib_src, lib_dst) # We have to", "don't want to archive. if PAT_MACOS_LIB_EXCLUDE.search(resolved_path): continue # Archive the rest of the", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "splits[1] if len(splits) > 1 else None if state == PARSING_NEW_RECORD: if key", "all dependencies of the executable referenced by 'target' from the build directory into", "target_dst, config): \"\"\" See relocate_deps(). Linux implementation. \"\"\" NEW_RPATH = '$ORIGIN/../lib' # Make", "well for transitive # dependencies to be properly resolved. $ORIGIN is always relative", "os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy the", "if state == PARSING_LIB_PATHS and cmd_type == LC_LOAD_DYLIB: if key == KEY_NAME: values.append(val)", "kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl| libgcc.* )\\.so\"\"\", re.VERBOSE) #", "KEY_NAME = 'name' KEY_PATH = 'path' # Exclude libraries that are GPL-licensed and", "dependencies to be properly resolved. $ORIGIN is always relative to the # running", "re import shutil import subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add", "if needed. prep_artifact_dirs(config) # Copy the target into the artifact directory. target_src =", "original to resolved library paths on success. If any libraries cannot be resolved,", "may look like: @rpath/Foo.framework/Versions/A/Foo 'dump' is the output from objdump_private_headers(). \"\"\" # Parsing", "= os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path, lib_dst) # Change library search path or name for", "or name for each archived library. modified_search_name = re.sub('^.*/', '@rpath/', search_name) subprocess.check_call(['install_name_tool', '-change',", "in the MachO header, without being first resolved to an absolute path, and", "the executable referenced by 'target' from the build directory into the artifact directory,", "the linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True)", "for convenient plumbing of path information. \"\"\" config = {} config[BUILD_ROOT] = build_root", "path 'dest'. If 'src' is a symlink, the link will be followed and", "target_dst = os.path.join(config[ARTIFACT_BIN_DIR], target) copy_file(target_src, target_dst) # Make the target relocatable and copy", "look for its # dependencies in a relative location. chrpath(target_dst, NEW_RPATH) def relocate_deps_macos(target_src,", "executable is invoked. \"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config) # Copy", "The resulting binaries should never # be deployed to run an actual Kudu", "library dependencies of the given binary. See resolve_library_paths_macos(). \"\"\" dump = objdump_private_headers(binary_path) raw_library_paths", "copy_file(target_src, target_dst) # Make the target relocatable and copy all of its dependencies", "dependencies are copied from the build # system and will not be updated", "\"\"\" resolved_paths = {} for raw_lib_path in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] =", "copy_file(src, dest): \"\"\" Copy the file with path 'src' to path 'dest'. If", "\"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config) # Copy the target into", "file except in compliance # with the License. You may obtain a copy", "the target into the artifact directory. target_src = os.path.join(config[BUILD_BIN_DIR], target) target_dst = os.path.join(config[ARTIFACT_BIN_DIR],", "executable itself to look for its # dependencies in a relative location. chrpath(target_dst,", "dest) def chrpath(target, new_rpath): \"\"\" Change the RPATH or RUNPATH for the specified", "portable # across Linux kernel versions. PAT_LINUX_LIB_EXCLUDE = re.compile(r\"\"\"(libpthread| libc| libstdc\\+\\+| librt| libdl|", "to set the RUNPATH of the shared objects as well for transitive #", "def parse_objdump_macos(cmd_type, dump): \"\"\" Parses the output from objdump_private_headers() for macOS. 'cmd_type' must", "rpath in rpaths: subprocess.check_call(['install_name_tool', '-delete_rpath', rpath, target_dst]) subprocess.check_call(['install_name_tool', '-add_rpath', '@executable_path/../lib', target_dst]) def relocate_deps(target_src,", "path 'src' to path 'dest'. If 'src' is a symlink, the link will", "we assume may not be portable between macOS versions. # TODO(mpercy): consider excluding", "are returned as stored in the MachO header, without being first resolved to", "the artifact root to ensure a clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets", "\"\"\" # Continue with a warning if no rpath is set on the", "set the RUNPATH of the shared objects as well for transitive # dependencies", "objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the given binary. Returns a list with", "maxsplit=2) key = splits[0] val = splits[1] if len(splits) > 1 else None", "return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns a map of symbolic to resolved library", "the target relocatable and copy all of its dependencies into the # artifact", "file # distributed with this work for additional information # regarding copyright ownership.", "# Licensed to the Apache Software Foundation (ASF) under one # or more", "is set on the binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err:", "copyright ownership. The ASF licenses this file # to you under the Apache", "ownership. The ASF licenses this file # to you under the Apache License,", "rpaths): \"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths", "clean build. if os.path.exists(artifact_root): shutil.rmtree(artifact_root) logging.info(\"Including targets and their dependencies in archive...\") config", "given binary. Returns a list with one line of objdump output per record.", "# Unless required by applicable law or agreed to in writing, # software", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "updated if the operating system on the runtime host is # patched. ################################################################################", "state enum values. PARSING_NONE = 0 PARSING_NEW_RECORD = 1 PARSING_RPATH = 2 PARSING_LIB_PATHS", "agreed to in writing, # software distributed under the License is distributed on", "os.path.join(build_root, \"bin\") config[ARTIFACT_ROOT] = artifact_root config[ARTIFACT_BIN_DIR] = os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\")", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "os.path.exists(config[ARTIFACT_BIN_DIR]): os.makedirs(config[ARTIFACT_BIN_DIR], mode=0755) if not os.path.exists(config[ARTIFACT_LIB_DIR]): os.makedirs(config[ARTIFACT_LIB_DIR], mode=0755) def copy_file(src, dest): \"\"\" Copy", "want to ship libSystem because it includes kernel and thread # routines that", "and change the rpath of the executable so that the copied dependencies will", "\"build-support\")) from kudu_util import check_output, Colors, init_logging from dep_extract import DependencyExtractor # Constants.", "to the Apache Software Foundation (ASF) under one # or more contributor license", "= objdump_private_headers(binary_path) return parse_objdump_macos(LC_RPATH, dump) def resolve_library_paths_macos(raw_library_paths, rpaths): \"\"\" Resolve the library paths", "import check_output, Colors, init_logging from dep_extract import DependencyExtractor # Constants. LC_RPATH = 'LC_RPATH'", "to ship libSystem because it includes kernel and thread # routines that we", "Kudu service, whether in production or # development, because all security dependencies are", "config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create any required artifact", "[] for line in dump: if re.match('^Load command', line): state = PARSING_NEW_RECORD continue", "specific language governing permissions and limitations # under the License. ################################################################################ # This", "Software Foundation (ASF) under one # or more contributor license agreements. See the", "\"-p\", binary_path]) except subprocess.CalledProcessError as err: logging.error(err) return [] return output.strip().decode(\"utf-8\").split(\"\\n\") def parse_objdump_macos(cmd_type,", "linked libraries. dep_extractor = DependencyExtractor() dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs", "the License is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "\"\"\" Resolve the library paths from parse_objdump_macos(LC_LOAD_DYLIB, ...) to absolute filesystem paths using", "system path so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output,", "def prep_artifact_dirs(config): \"\"\" Create any required artifact output directories, if needed. \"\"\" if", "Continue with a warning if no rpath is set on the binary. try:", "that we assume may not be portable between macOS versions. # TODO(mpercy): consider", "continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1] if", "# Strip trailing metadata from rpath dump line. values.append(val) if state == PARSING_LIB_PATHS", "be portable between macOS versions. # TODO(mpercy): consider excluding libc++ as well. PAT_MACOS_LIB_EXCLUDE", "arch) return artifact_name def mkconfig(build_root, artifact_root): \"\"\" Build a configuration map for convenient", "rpaths = parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive", "'target' from the build directory into the artifact directory, and change the rpath", "= get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems(): # Filter out libs we", "relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src) check_for_command('install_name_tool') for (search_name, resolved_path) in libs.iteritems():", "get_artifact_name(): \"\"\" Create an archive with an appropriate name. Including version, OS, and", "containing the rpath search path, with one search path per entry. * LC_LOAD_DYLIB:", "dep_extractor.set_library_filter(lambda path: False if PAT_LINUX_LIB_EXCLUDE.search(path) else True) libs = dep_extractor.extract_deps(target_src) for lib_src in", "relocate_deps(target_src, target_dst, config): \"\"\" Make the target relocatable and copy all of its", "kudu_build_dir target [target ...]\" % (sys.argv[0], )) sys.exit(1) # Command-line arguments. build_root =", "Apache License, Version 2.0 (the # \"License\"); you may not use this file", "KEY_CMD = 'cmd' KEY_NAME = 'name' KEY_PATH = 'path' # Exclude libraries that", "Including version, OS, and architecture. \"\"\" if IS_LINUX: os_str = \"linux\" elif IS_MACOS:", "Change the RPATH or RUNPATH for the specified target. See man chrpath(1). \"\"\"", "kernel and thread # routines that we assume may not be portable between", "is the output from objdump_private_headers(). \"\"\" # Parsing state enum values. PARSING_NONE =", "%s command\", command) raise err def objdump_private_headers(binary_path): \"\"\" Run `objdump -p` on the", "PARSING_NEW_RECORD continue splits = re.split('\\s+', line.strip().decode(\"utf-8\"), maxsplit=2) key = splits[0] val = splits[1]", "binary. try: subprocess.check_call(['chrpath', '-l', target]) except subprocess.CalledProcessError as err: logging.warning(\"No RPATH or RUNPATH", "version: version = version.readline().strip().decode(\"utf-8\") artifact_name = \"kudu-binary-%s-%s-%s\" % (version, os_str, arch) return artifact_name", "sys.argv[2:] init_logging() if not os.path.exists(build_root): logging.error(\"Build directory %s does not exist\", build_root) sys.exit(1)", "path information. \"\"\" config = {} config[BUILD_ROOT] = build_root config[BUILD_BIN_DIR] = os.path.join(build_root, \"bin\")", "in raw_library_paths: if not raw_lib_path.startswith(\"@rpath\"): resolved_paths[raw_lib_path] = raw_lib_path continue resolved = False for", "subprocess import sys SOURCE_ROOT = os.path.join(os.path.dirname(__file__), \"../..\") # Add the build-support dir to", "so we can import kudu-util. sys.path.append(os.path.join(SOURCE_ROOT, \"build-support\")) from kudu_util import check_output, Colors, init_logging", "= os.path.join(artifact_root, \"bin\") config[ARTIFACT_LIB_DIR] = os.path.join(artifact_root, \"lib\") return config def prep_artifact_dirs(config): \"\"\" Create", "will not be updated if the operating system on the runtime host is", "parse_objdump_macos(LC_RPATH, dump) return resolve_library_paths_macos(raw_library_paths, rpaths) def get_artifact_name(): \"\"\" Create an archive with an", "# Archive the rest of the runtime dependencies. lib_dst = os.path.join(config[ARTIFACT_LIB_DIR], os.path.basename(resolved_path)) copy_file(resolved_path,", "the executable is invoked. \"\"\" # Create artifact directories, if needed. prep_artifact_dirs(config) #", "os_str = \"osx\" else: raise NotImplementedError(\"Unsupported platform\") arch = os.uname()[4] with open(os.path.join(SOURCE_ROOT, \"version.txt\"),", "main(): if len(sys.argv) < 3: print(\"Usage: %s kudu_build_dir target [target ...]\" % (sys.argv[0],", "%s in rpath %s\" % (raw_lib_path, rpaths)) return resolved_paths def get_dep_library_paths_macos(binary_path): \"\"\" Returns", "def relocate_deps_macos(target_src, target_dst, config): \"\"\" See relocate_deps(). macOS implementation. \"\"\" libs = get_dep_library_paths_macos(target_src)" ]
[ "0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber) currentNumber += 1 print sum(primeList)", "currentNumber = 0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber) currentNumber += 1", "__name__ == '__main__': primeList = [] currentNumber = 0 while len(primeList) < 1000:", "each other, then that means that this #one is prime. Also, 2 <=", "theorem a^n (mod n) = a (mod n). #If they equal each other,", "% 2 == 0): #Use Fermat's little theorem a^n (mod n) = a", "they equal each other, then that means that this #one is prime. Also,", "determine the sum of the first 1000 prime numbers. ''' import random import", "sum of the first 1000 prime numbers. ''' import random import math def", "that this #one is prime. Also, 2 <= a < n where a", "result = False elif not num == 2: result = False return result", "means that this #one is prime. Also, 2 <= a < n where", "file is to determine the sum of the first 1000 prime numbers. '''", "first 1000 prime numbers. ''' import random import math def isPrime(num): result =", "not num == 2: result = False return result if __name__ == '__main__':", "% num) == (a % num): sqrt_n = math.sqrt(num) for divider in range(3,", "divider == 0: result = False break else: result = False elif not", "primeList = [] currentNumber = 0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber)", "num - 1) if ((a ** num) % num) == (a % num):", "in range(3, int(math.ceil(sqrt_n) + 1)): if num % divider == 0: result =", "a < n where a is an integer a = random.randint(2, num -", "result if __name__ == '__main__': primeList = [] currentNumber = 0 while len(primeList)", "result = False break else: result = False elif not num == 2:", "< n where a is an integer a = random.randint(2, num - 1)", "(num % 2 == 0): #Use Fermat's little theorem a^n (mod n) =", "this file is to determine the sum of the first 1000 prime numbers.", "num) % num) == (a % num): sqrt_n = math.sqrt(num) for divider in", "((a ** num) % num) == (a % num): sqrt_n = math.sqrt(num) for", "''' import random import math def isPrime(num): result = True if num >", "sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)): if num %", "num % divider == 0: result = False break else: result = False", "2 == 0): #Use Fermat's little theorem a^n (mod n) = a (mod", "2: result = False return result if __name__ == '__main__': primeList = []", "if __name__ == '__main__': primeList = [] currentNumber = 0 while len(primeList) <", "1) if ((a ** num) % num) == (a % num): sqrt_n =", "= 0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber) currentNumber += 1 print", "Also, 2 <= a < n where a is an integer a =", "False return result if __name__ == '__main__': primeList = [] currentNumber = 0", "is to determine the sum of the first 1000 prime numbers. ''' import", "True if num > 2 and not (num % 2 == 0): #Use", "elif not num == 2: result = False return result if __name__ ==", "prime numbers. ''' import random import math def isPrime(num): result = True if", "== '__main__': primeList = [] currentNumber = 0 while len(primeList) < 1000: if", "a (mod n). #If they equal each other, then that means that this", "+ 1)): if num % divider == 0: result = False break else:", "- 1) if ((a ** num) % num) == (a % num): sqrt_n", "that means that this #one is prime. Also, 2 <= a < n", "(a % num): sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)):", "not (num % 2 == 0): #Use Fermat's little theorem a^n (mod n)", "% divider == 0: result = False break else: result = False elif", "0): #Use Fermat's little theorem a^n (mod n) = a (mod n). #If", "% num): sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)): if", "range(3, int(math.ceil(sqrt_n) + 1)): if num % divider == 0: result = False", "'__main__': primeList = [] currentNumber = 0 while len(primeList) < 1000: if isPrime(currentNumber):", "the first 1000 prime numbers. ''' import random import math def isPrime(num): result", "Focus of this file is to determine the sum of the first 1000", "is prime. Also, 2 <= a < n where a is an integer", "then that means that this #one is prime. Also, 2 <= a <", "import math def isPrime(num): result = True if num > 2 and not", "(mod n) = a (mod n). #If they equal each other, then that", "numbers. ''' import random import math def isPrime(num): result = True if num", "a^n (mod n) = a (mod n). #If they equal each other, then", "result = True if num > 2 and not (num % 2 ==", "this #one is prime. Also, 2 <= a < n where a is", "to determine the sum of the first 1000 prime numbers. ''' import random", "num) == (a % num): sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n)", "int(math.ceil(sqrt_n) + 1)): if num % divider == 0: result = False break", "#one is prime. Also, 2 <= a < n where a is an", "if num % divider == 0: result = False break else: result =", "0: result = False break else: result = False elif not num ==", "of the first 1000 prime numbers. ''' import random import math def isPrime(num):", "random.randint(2, num - 1) if ((a ** num) % num) == (a %", "num): sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)): if num", "where a is an integer a = random.randint(2, num - 1) if ((a", "(mod n). #If they equal each other, then that means that this #one", "False break else: result = False elif not num == 2: result =", "= True if num > 2 and not (num % 2 == 0):", "num == 2: result = False return result if __name__ == '__main__': primeList", "a = random.randint(2, num - 1) if ((a ** num) % num) ==", "Fermat's little theorem a^n (mod n) = a (mod n). #If they equal", "== 2: result = False return result if __name__ == '__main__': primeList =", "num > 2 and not (num % 2 == 0): #Use Fermat's little", "for divider in range(3, int(math.ceil(sqrt_n) + 1)): if num % divider == 0:", "2 <= a < n where a is an integer a = random.randint(2,", "integer a = random.randint(2, num - 1) if ((a ** num) % num)", "import random import math def isPrime(num): result = True if num > 2", "if num > 2 and not (num % 2 == 0): #Use Fermat's", "result = False return result if __name__ == '__main__': primeList = [] currentNumber", "other, then that means that this #one is prime. Also, 2 <= a", "equal each other, then that means that this #one is prime. Also, 2", "== (a % num): sqrt_n = math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) +", "an integer a = random.randint(2, num - 1) if ((a ** num) %", "[] currentNumber = 0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber) currentNumber +=", "n where a is an integer a = random.randint(2, num - 1) if", "1)): if num % divider == 0: result = False break else: result", "<= a < n where a is an integer a = random.randint(2, num", "** num) % num) == (a % num): sqrt_n = math.sqrt(num) for divider", "return result if __name__ == '__main__': primeList = [] currentNumber = 0 while", "isPrime(num): result = True if num > 2 and not (num % 2", "else: result = False elif not num == 2: result = False return", "= False break else: result = False elif not num == 2: result", "prime. Also, 2 <= a < n where a is an integer a", "#Use Fermat's little theorem a^n (mod n) = a (mod n). #If they", "math def isPrime(num): result = True if num > 2 and not (num", "= [] currentNumber = 0 while len(primeList) < 1000: if isPrime(currentNumber): primeList.append(currentNumber) currentNumber", "''' Focus of this file is to determine the sum of the first", "#If they equal each other, then that means that this #one is prime.", "is an integer a = random.randint(2, num - 1) if ((a ** num)", "== 0): #Use Fermat's little theorem a^n (mod n) = a (mod n).", "if ((a ** num) % num) == (a % num): sqrt_n = math.sqrt(num)", "2 and not (num % 2 == 0): #Use Fermat's little theorem a^n", "break else: result = False elif not num == 2: result = False", "= a (mod n). #If they equal each other, then that means that", "1000 prime numbers. ''' import random import math def isPrime(num): result = True", "of this file is to determine the sum of the first 1000 prime", "n). #If they equal each other, then that means that this #one is", "False elif not num == 2: result = False return result if __name__", "and not (num % 2 == 0): #Use Fermat's little theorem a^n (mod", "the sum of the first 1000 prime numbers. ''' import random import math", "> 2 and not (num % 2 == 0): #Use Fermat's little theorem", "math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)): if num % divider ==", "= random.randint(2, num - 1) if ((a ** num) % num) == (a", "n) = a (mod n). #If they equal each other, then that means", "= math.sqrt(num) for divider in range(3, int(math.ceil(sqrt_n) + 1)): if num % divider", "def isPrime(num): result = True if num > 2 and not (num %", "random import math def isPrime(num): result = True if num > 2 and", "little theorem a^n (mod n) = a (mod n). #If they equal each", "= False return result if __name__ == '__main__': primeList = [] currentNumber =", "divider in range(3, int(math.ceil(sqrt_n) + 1)): if num % divider == 0: result", "a is an integer a = random.randint(2, num - 1) if ((a **", "= False elif not num == 2: result = False return result if", "== 0: result = False break else: result = False elif not num" ]
[ "input_text_end is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size,", "num_hidden: number of hidden GRU cells in every layer :param int num_layers: number", "variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits", "self.remove_padding(variation) # create the embeddings # first vector is a zeros vector used", "axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997,", "sequence_length_end = None variation, variation_length = self.remove_padding(variation) # create the embeddings # first", "def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope", "dataset :param List[List[float]] embeddings: a matrix with the embeddings for the embedding lookup", "shape as input_text or even a constant shape :param embeddings: :param input_text: :return:", "input_text): # calculate max length of the input_text mask = tf.greater_equal(input_text, 0) #", "text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length", "\"\"\" Creates a learning rate and an optimizer for the loss :param tf.Tensor", "classifier :param int batch_size: batch size, the same used in the dataset :param", ":param List[List[float]] embeddings: a matrix with the embeddings for the embedding lookup :param", "for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text to", "batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self,", "one hot encoding labels :return tf.Tensor : a tensor with the loss value", "1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not", "self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else: output", "mask = tf.greater_equal(input_text, 0) # true for words false for padding sequence_length =", ":return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None:", "net = tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net =", "the text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number of output", "= optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__ == '__main__': main(ModelSimple(), 'simple', batch_size=TC_BATCH_SIZE)", "the number of steps to decay the learning rate :return (tf.Tensor, tf.Tensor): a", "of the model :param float dropout: dropout value between layers :param boolean training:", "self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is not None: with tf.variable_scope('text_end'):", "\"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end =", "the decay of the learning rate :param int learning_rate_decay_steps: the number of steps", "embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation", "labels :return tf.Tensor : a tensor with the loss value \"\"\" logits =", "num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for _ in range(num_layers): cell =", "the embeddings and the input text returns the embedded sequence and the sequence", "None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene,", "the embeddings for the embedding lookup :param int num_hidden: number of hidden GRU", "output embedded_sequence wont have the same shape as input_text or even a constant", "and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate')", "tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene,", "for training or not :return Dict[str,tf.Tensor]: a dict with logits and prediction tensors", "tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data): \"\"\" Calculates the softmax cross", "loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an optimizer", "input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end = tf.add(input_text_end,", "number of steps to decay the learning rate :return (tf.Tensor, tf.Tensor): a tuple", "cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT):", "num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for _ in range(num_layers): cell", "= len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings',", "num_output_classes: the number of output classes for the classifier :param int batch_size: batch", "encoding labels :param tf.Tensor labels: an array of labels with dimension [batch_size] :param", "else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation", "to decay the learning rate :return (tf.Tensor, tf.Tensor): a tuple with the optimizer", "is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene =", "input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation", "= None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings,", "= tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin,", ":param tf.Tensor global_step: the global step for training :param int learning_rate_initial: the initial", "not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output", "layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): # calculate max length of", "optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer", "output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1)", "= tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation =", "# optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__", "the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end =", "prediction, } def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): #", "a learning rate and an optimizer for the loss :param tf.Tensor loss: the", "_ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell)", "def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates", "embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need to add", "input text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght =", "the sequence length. The input_text is truncated to the max length of the", ":param tf.Tensor labels: an array of labels with dimension [batch_size] :param int output_classes:", "for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the", "of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings,", "training or not :return Dict[str,tf.Tensor]: a dict with logits and prediction tensors \"\"\"", "learning rate :return (tf.Tensor, tf.Tensor): a tuple with the optimizer and the learning", "sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else: output =", "\"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return", "tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation,", "wont have the same shape as input_text or even a constant shape :param", "on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data): \"\"\"", "the loss of the model :param tf.Tensor global_step: the global step for training", "between layers :param boolean training: whether the model is built for training or", "the same used in the dataset :param List[List[float]] embeddings: a matrix with the", "the model :param float dropout: dropout value between layers :param boolean training: whether", "same shape as input_text or even a constant shape :param embeddings: :param input_text:", "the embeddings # first vector is a zeros vector used for padding embeddings_dimension", "tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end", "tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer", "targets def loss(self, targets, graph_data): \"\"\" Calculates the softmax cross entropy loss :param", "depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data):", "embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene", "learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer", "* from .text_classification_train import main class ModelSimple(object): \"\"\" Base class to create models", "labels into a matrix of one hot encoding labels :param tf.Tensor labels: an", "input_text mask = tf.greater_equal(input_text, 0) # true for words false for padding sequence_length", "None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length = self.remove_padding(variation)", "\"\"\" Base class to create models for text classification. It uses several layers", "text returns the embedded sequence and the sequence length. The input_text is truncated", "logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN,", "= tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length", ":param tf.Tensor logits: logits output of the model :param tf.Tensor targets: targets with", "sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of the dynamic_rnn sequence_output", "tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output", "embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with", "batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else: output = output_begin # full", "= tf.greater_equal(input_text, 0) # true for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask,", "of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size)", "return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the", "prediction = tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction, } def rnn(self,", "dropout value between layers :param boolean training: whether the model is built for", "a matrix of one hot encoding labels :param tf.Tensor labels: an array of", "_ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of", "variation): \"\"\" Given the embeddings and the input text returns the embedded sequence", "get last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden])", "\"\"\" Calculates the softmax cross entropy loss :param tf.Tensor logits: logits output of", ":param int num_hidden: number of hidden GRU cells in every layer :param int", "used for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings", "# full connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction", "embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation", "a vector of labels into a matrix of one hot encoding labels :param", "targets, graph_data): \"\"\" Calculates the softmax cross entropy loss :param tf.Tensor logits: logits", "None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output =", "layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text):", "global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer =", "Given the embeddings and the input text returns the embedded sequence and the", "empty_padding_lenght = input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return", "tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need to add 1 to the", "means we need to add 1 to the input_text input_text_begin = tf.add(input_text_begin, 1)", "tf from tensorflow.contrib import slim import tensorflow.contrib.layers as layers from ..configuration import *", "sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None)", "learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate)", "tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def loss(self,", "true for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate", "activation_fn=None) as scope: return scope def targets(self, labels, output_classes): \"\"\" Transform a vector", "for the loss :param tf.Tensor loss: the tensor with the loss of the", "embeddings_size] :param int num_output_classes: the number of output classes for the classifier :param", "with dimension [batch_size] :param int output_classes: the total number of output classes :return", "input_text_end, gene, variation): \"\"\" Given the embeddings and the input text returns the", "output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1) net =", "the optimizer and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay,", "int learning_rate_initial: the initial learning rate :param int learning_rate_decay: the decay of the", "class to create models for text classification. It uses several layers of GRU", "with the loss value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return", "with the optimizer and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps,", "max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self,", ":param int learning_rate_initial: the initial learning rate :param int learning_rate_decay: the decay of", "+ embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need to", "1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings,", "num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction,", "of the input_text mask = tf.greater_equal(input_text, 0) # true for words false for", "_ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training)", "is a zeros vector used for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0]", "tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end", "embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need to add 1", "net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net,", "the global step for training :param int learning_rate_initial: the initial learning rate :param", "input_text is truncated to the max length of the sequence, so the output", "tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network,", "hot encoding labels :param tf.Tensor labels: an array of labels with dimension [batch_size]", "input_text: the input data, the text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes:", "tensorflow.contrib import slim import tensorflow.contrib.layers as layers from ..configuration import * from .text_classification_train", "of labels into a matrix of one hot encoding labels :param tf.Tensor labels:", "tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1)", "None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene)", "gene, variation): \"\"\" Given the embeddings and the input text returns the embedded", "name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer =", "input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end = tf.add(input_text_end, 1)", "embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _,", "self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end =", "net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def", "input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end = tf.reshape(input_text_end,", "a matrix with the embeddings for the embedding lookup :param int num_hidden: number", "of the model :param tf.Tensor global_step: the global step for training :param int", "the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') #", "axis=1) else: output = output_begin # full connected layer logits = self.model_fully_connected(output, gene,", "output = tf.concat([output_begin, output_end], axis=1) else: output = output_begin # full connected layer", "learning_rate_initial: the initial learning rate :param int learning_rate_decay: the decay of the learning", "labels :param tf.Tensor labels: an array of labels with dimension [batch_size] :param int", "\"\"\" Given the embeddings and the input text returns the embedded sequence and", "sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) * max_length +", "loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS):", "dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1)", "tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets,", "loss value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def", ":param float dropout: dropout value between layers :param boolean training: whether the model", "return logits def remove_padding(self, input_text): # calculate max length of the input_text mask", "0) # true for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1)", "input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene", "initial learning rate :param int learning_rate_decay: the decay of the learning rate :param", "dtype=tf.float32) # this means we need to add 1 to the input_text input_text_begin", "It uses several layers of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene,", "tf.Tensor global_step: the global step for training :param int learning_rate_initial: the initial learning", "as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number of output classes for", "an array of labels with dimension [batch_size] :param int output_classes: the total number", "max length of the sequence, so the output embedded_sequence wont have the same", "training) prediction = tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction, } def", "the input text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght", "output = output_begin # full connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes,", "training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for _ in range(num_layers):", "cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells)", "classification :param tf.Tensor input_text: the input data, the text as [batch_size, text_vector_max_length, embeddings_size]", "graph_data): \"\"\" Calculates the softmax cross entropy loss :param tf.Tensor logits: logits output", "so the output embedded_sequence wont have the same shape as input_text or even", "layers of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size,", "vector of labels into a matrix of one hot encoding labels :param tf.Tensor", "of one hot encoding labels :param tf.Tensor labels: an array of labels with", "graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY,", "= tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end", "if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None", "gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1)", "learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an optimizer for the loss", "embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end)", "Creates a model for text classification :param tf.Tensor input_text: the input data, the", "value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self,", "variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene,", "layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128,", "return scope def targets(self, labels, output_classes): \"\"\" Transform a vector of labels into", "for text classification :param tf.Tensor input_text: the input data, the text as [batch_size,", "data, the text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number of", "every layer :param int num_layers: number of layers of the model :param float", "num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length - 1) output = tf.gather(sequence_output,", "= layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes,", "def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network.", "the initial learning rate :param int learning_rate_decay: the decay of the learning rate", "with the embeddings for the embedding lookup :param int num_hidden: number of hidden", "batch_size: batch size, the same used in the dataset :param List[List[float]] embeddings: a", "of the sequence, so the output embedded_sequence wont have the same shape as", "output_classes): \"\"\" Transform a vector of labels into a matrix of one hot", "if input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\", "as input_text or even a constant shape :param embeddings: :param input_text: :return: (embedded_sequence,", "= tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin =", "variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length,", "is not None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation =", "the one hot encoding labels :return tf.Tensor : a tensor with the loss", "= tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss,", "total number of output classes :return tf.Tensor: a tensorflow tensor \"\"\" targets =", "\\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as", "several layers of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes,", "batch_size, training) if input_text_end is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end,", "even a constant shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin,", "= tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght],", "the number of output classes for the classifier :param int batch_size: batch size,", "not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings,", "tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets", "= tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__ == '__main__':", "variation, variation_length = self.remove_padding(variation) # create the embeddings # first vector is a", "learning rate :param int learning_rate_decay: the decay of the learning rate :param int", "matrix with the embeddings for the embedding lookup :param int num_hidden: number of", "sequence and the sequence length. The input_text is truncated to the max length", "value between layers :param boolean training: whether the model is built for training", ":param int batch_size: batch size, the same used in the dataset :param List[List[float]]", ":param int num_output_classes: the number of output classes for the classifier :param int", "sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length = self.remove_padding(variation) # create", "= tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end", "softmax cross entropy loss :param tf.Tensor logits: logits output of the model :param", "[batch_size] :param int output_classes: the total number of output classes :return tf.Tensor: a", "not :return Dict[str,tf.Tensor]: a dict with logits and prediction tensors \"\"\" input_text_begin =", "have the same shape as input_text or even a constant shape :param embeddings:", "global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an optimizer for", "length. The input_text is truncated to the max length of the sequence, so", ":param int learning_rate_decay_steps: the number of steps to decay the learning rate :return", "tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step)", "sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells =", "in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network", "axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given", "not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length =", "from ..configuration import * from .text_classification_train import main class ModelSimple(object): \"\"\" Base class", "sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm],", "tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if", "MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin,", "tf.range(batch_size) * max_length + (sequence_length - 1) output = tf.gather(sequence_output, indexes) return output", "cross entropy loss :param tf.Tensor logits: logits output of the model :param tf.Tensor", "input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length = self.remove_padding(variation) #", "not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\", "sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end", "(tf.Tensor, tf.Tensor): a tuple with the optimizer and the learning rate \"\"\" learning_rate", "tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is", "variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification", "of the learning rate :param int learning_rate_decay_steps: the number of steps to decay", "model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a", "rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells", "the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) *", "not None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation = tf.add(variation,", "int batch_size: batch size, the same used in the dataset :param List[List[float]] embeddings:", "= tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _ =", "sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last", "input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin", "tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is not", "the output embedded_sequence wont have the same shape as input_text or even a", "input_text or even a constant shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length)", "dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) * max_length", "variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin))", "for training :param int learning_rate_initial: the initial learning rate :param int learning_rate_decay: the", "a tuple with the optimizer and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial,", "batch size, the same used in the dataset :param List[List[float]] embeddings: a matrix", "the input text returns the embedded sequence and the sequence length. The input_text", "max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size,", "staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer", "max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else: output = output_begin", "type)) # get last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size *", "output_end], axis=1) else: output = output_begin # full connected layer logits = self.model_fully_connected(output,", "[batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length - 1)", "optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer =", "gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text", "tf.Tensor): a tuple with the optimizer and the learning rate \"\"\" learning_rate =", ":param boolean training: whether the model is built for training or not :return", "\"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer =", "= self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length = self.remove_padding(variation) # create the", "input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1)", "is_training=training) net = tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net", "def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings and the", "tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end =", "the model :param tf.Tensor targets: targets with the one hot encoding labels :return", "learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) #", "training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification :param tf.Tensor input_text: the", "logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step,", "sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings and", "of output classes for the classifier :param int batch_size: batch size, the same", "= layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net,", "input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for", "Creates a learning rate and an optimizer for the loss :param tf.Tensor loss:", "= tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def", "connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits)", "logits output of the model :param tf.Tensor targets: targets with the one hot", "learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate)", "Recurrent network. cells = [] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if", "remove_padding(self, input_text): # calculate max length of the input_text mask = tf.greater_equal(input_text, 0)", "tuple with the optimizer and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step,", "variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return { 'logits' : logits, 'prediction':", "embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon,", "= None variation, variation_length = self.remove_padding(variation) # create the embeddings # first vector", "truncate the input text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1]", "embeddings and the input text returns the embedded sequence and the sequence length.", "int learning_rate_decay: the decay of the learning rate :param int learning_rate_decay_steps: the number", "1) # truncate the input text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length", ": a tensor with the loss value \"\"\" logits = graph_data['logits'] loss =", "axis=1) return targets def loss(self, targets, graph_data): \"\"\" Calculates the softmax cross entropy", "# true for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) #", "\\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation)", "layers from ..configuration import * from .text_classification_train import main class ModelSimple(object): \"\"\" Base", "output_begin # full connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training)", "= tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size,", "input data, the text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number", "array of labels with dimension [batch_size] :param int output_classes: the total number of", "an optimizer for the loss :param tf.Tensor loss: the tensor with the loss", "sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output", "max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _", "from .text_classification_train import main class ModelSimple(object): \"\"\" Base class to create models for", "sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = []", "max length of the input_text mask = tf.greater_equal(input_text, 0) # true for words", ":return (tf.Tensor, tf.Tensor): a tuple with the optimizer and the learning rate \"\"\"", "tf.Tensor : a tensor with the loss value \"\"\" logits = graph_data['logits'] loss", "sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else:", "= tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data): \"\"\" Calculates the softmax", "false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text", "1 to the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not None:", "tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout,", "tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length,", "* max_length + (sequence_length - 1) output = tf.gather(sequence_output, indexes) return output def", "training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1) net", "input_text_begin, input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin =", "loss(self, targets, graph_data): \"\"\" Calculates the softmax cross entropy loss :param tf.Tensor logits:", "tf.Tensor targets: targets with the one hot encoding labels :return tf.Tensor : a", "and the sequence length. The input_text is truncated to the max length of", "input_text_begin) if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end =", "the softmax cross entropy loss :param tf.Tensor logits: logits output of the model", "logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return {", "output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes =", "padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text to max", "tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type =", "to the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end", "of the model :param tf.Tensor targets: targets with the one hot encoding labels", "to add 1 to the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is", "create the embeddings # first vector is a zeros vector used for padding", "return output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output = layers.dropout(output,", "input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings,", "= layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self,", "input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation,", "if input_text_end is not None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1)", "# get last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length,", "import tensorflow as tf from tensorflow.contrib import slim import tensorflow.contrib.layers as layers from", "output_classes: the total number of output classes :return tf.Tensor: a tensorflow tensor \"\"\"", "= tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\"", "embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end,", "batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification :param tf.Tensor", "model for text classification :param tf.Tensor input_text: the input data, the text as", "\"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end =", "layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return", "embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need", "tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end", "type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) #", "tensor with the loss value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits)", "the total number of output classes :return tf.Tensor: a tensorflow tensor \"\"\" targets", "the embedding lookup :param int num_hidden: number of hidden GRU cells in every", "need to add 1 to the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end", "create models for text classification. It uses several layers of GRU cells. \"\"\"", "tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate", "labels, output_classes): \"\"\" Transform a vector of labels into a matrix of one", "of hidden GRU cells in every layer :param int num_layers: number of layers", "for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings", "dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of the dynamic_rnn sequence_output =", "with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin,", "= [] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell =", "or even a constant shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\"", "= tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end,", "\"\"\" Creates a model for text classification :param tf.Tensor input_text: the input data,", "self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin", "= graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL,", "embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end,", "embedded sequence and the sequence length. The input_text is truncated to the max", "# create the embeddings # first vector is a zeros vector used for", "GRU cells in every layer :param int num_layers: number of layers of the", "float dropout: dropout value between layers :param boolean training: whether the model is", "* embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we", "output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence,", "= tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size,", "[batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings,", "rate :return (tf.Tensor, tf.Tensor): a tuple with the optimizer and the learning rate", "full connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction =", ":param tf.Tensor targets: targets with the one hot encoding labels :return tf.Tensor :", "model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings and the input", "..configuration import * from .text_classification_train import main class ModelSimple(object): \"\"\" Base class to", "import main class ModelSimple(object): \"\"\" Base class to create models for text classification.", "axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\", ":param int learning_rate_decay: the decay of the learning rate :param int learning_rate_decay_steps: the", "MAX_WORDS]) if input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin,", "words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input", "a zeros vector used for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] *", "targets: targets with the one hot encoding labels :return tf.Tensor : a tensor", "class ModelSimple(object): \"\"\" Base class to create models for text classification. It uses", "def targets(self, labels, output_classes): \"\"\" Transform a vector of labels into a matrix", "else: sequence_length_end = None variation, variation_length = self.remove_padding(variation) # create the embeddings #", "int num_output_classes: the number of output classes for the classifier :param int batch_size:", "sequence, so the output embedded_sequence wont have the same shape as input_text or", "labels with dimension [batch_size] :param int output_classes: the total number of output classes", "None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation = tf.add(variation, 1)", "[batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number of output classes for the", "input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end)", "Dict[str,tf.Tensor]: a dict with logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size,", "models for text classification. It uses several layers of GRU cells. \"\"\" def", ":param tf.Tensor input_text: the input data, the text as [batch_size, text_vector_max_length, embeddings_size] :param", "self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return { 'logits' :", ":param int num_layers: number of layers of the model :param float dropout: dropout", "into a matrix of one hot encoding labels :param tf.Tensor labels: an array", ":param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if", "= [[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this", "embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification :param tf.Tensor input_text:", "max_length, dropout, batch_size, training) if input_text_end is not None: with tf.variable_scope('text_end'): output_end =", "if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype", "of layers of the model :param float dropout: dropout value between layers :param", "= tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene =", "tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\", "as tf from tensorflow.contrib import slim import tensorflow.contrib.layers as layers from ..configuration import", "constant shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin =", "else: output = output_begin # full connected layer logits = self.model_fully_connected(output, gene, variation,", "calculate max length of the input_text mask = tf.greater_equal(input_text, 0) # true for", "a constant shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin", "text_vector_max_length, embeddings_size] :param int num_output_classes: the number of output classes for the classifier", "is built for training or not :return Dict[str,tf.Tensor]: a dict with logits and", "# truncate the input text to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length =", "padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings =", "learning_rate_decay: the decay of the learning rate :param int learning_rate_decay_steps: the number of", "tensorflow.contrib.layers as layers from ..configuration import * from .text_classification_train import main class ModelSimple(object):", "_, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout,", "we need to add 1 to the input_text input_text_begin = tf.add(input_text_begin, 1) if", "'logits' : logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length, dropout, batch_size,", "sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene,", "dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for _", "or not :return Dict[str,tf.Tensor]: a dict with logits and prediction tensors \"\"\" input_text_begin", "embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return", "network. cells = [] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training:", "cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _", "the model is built for training or not :return Dict[str,tf.Tensor]: a dict with", "tf.int32), 1) # truncate the input text to max length max_sequence_length = tf.reduce_max(sequence_length)", "boolean training: whether the model is built for training or not :return Dict[str,tf.Tensor]:", "length of the input_text mask = tf.greater_equal(input_text, 0) # true for words false", "output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout,", "None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation)", "the learning rate :return (tf.Tensor, tf.Tensor): a tuple with the optimizer and the", "the sequence, so the output embedded_sequence wont have the same shape as input_text", "= sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get", "decay of the learning rate :param int learning_rate_decay_steps: the number of steps to", "# this means we need to add 1 to the input_text input_text_begin =", "# calculate max length of the input_text mask = tf.greater_equal(input_text, 0) # true", "max_length, num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length - 1) output =", "'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS):", "this means we need to add 1 to the input_text input_text_begin = tf.add(input_text_begin,", "embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation =", "global step for training :param int learning_rate_initial: the initial learning rate :param int", "one hot encoding labels :param tf.Tensor labels: an array of labels with dimension", "scope: return scope def targets(self, labels, output_classes): \"\"\" Transform a vector of labels", "tensorflow as tf from tensorflow.contrib import slim import tensorflow.contrib.layers as layers from ..configuration", "the dataset :param List[List[float]] embeddings: a matrix with the embeddings for the embedding", "tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _ = tf.split(input_text,", "is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training)", "learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an optimizer for the", "= tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None: embedded_sequence_end = tf.nn.embedding_lookup(embeddings, input_text_end) else:", "is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): # calculate", "\"\"\" Transform a vector of labels into a matrix of one hot encoding", "initial_state=network.zero_state(batch_size, type)) # get last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size", "model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net", "axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def loss(self, targets,", "to the max length of the sequence, so the output embedded_sequence wont have", "cells in every layer :param int num_layers: number of layers of the model", "targets with the one hot encoding labels :return tf.Tensor : a tensor with", "= self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end", "logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is", "input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings and the input text returns", "len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32)", "the embedded sequence and the sequence length. The input_text is truncated to the", "last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes", "hidden GRU cells in every layer :param int num_layers: number of layers of", "tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type))", "GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True,", "tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text to max length max_sequence_length =", "for the embedding lookup :param int num_hidden: number of hidden GRU cells in", "encoding labels :return tf.Tensor : a tensor with the loss value \"\"\" logits", "= tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type", "tf.reshape(sequence_output, [batch_size * max_length, num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length -", "# optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return", "range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network =", "indexes = tf.range(batch_size) * max_length + (sequence_length - 1) output = tf.gather(sequence_output, indexes)", "= input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text,", "the loss :param tf.Tensor loss: the tensor with the loss of the model", "optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__ == '__main__': main(ModelSimple(), 'simple',", "keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu)", "slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self, labels, output_classes): \"\"\"", "_ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin,", "with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is", "with logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end", "embedded_sequence wont have the same shape as input_text or even a constant shape", "embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return", "int output_classes: the total number of output classes :return tf.Tensor: a tensorflow tensor", "training :param int learning_rate_initial: the initial learning rate :param int learning_rate_decay: the decay", "return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning", "= tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def", "tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin,", "return targets def loss(self, targets, graph_data): \"\"\" Calculates the softmax cross entropy loss", "dropout, batch_size, training) if input_text_end is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end,", "= layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): # calculate max length", "returns the embedded sequence and the sequence length. The input_text is truncated to", "gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return { 'logits' : logits,", "labels: an array of labels with dimension [batch_size] :param int output_classes: the total", "to max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length -", "classes for the classifier :param int batch_size: batch size, the same used in", "learning_rate_decay_steps: the number of steps to decay the learning rate :return (tf.Tensor, tf.Tensor):", "# Recurrent network. cells = [] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden)", ":param int output_classes: the total number of output classes :return tf.Tensor: a tensorflow", "model :param tf.Tensor targets: targets with the one hot encoding labels :return tf.Tensor", "classes :return tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0,", "input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length,", "variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene,", "input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin,", "1) if input_text_end is not None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene,", "with the loss of the model :param tf.Tensor global_step: the global step for", ":param tf.Tensor loss: the tensor with the loss of the model :param tf.Tensor", "is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length", "the input data, the text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the", "def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and", "= self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else:", "def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training)", "vector is a zeros vector used for padding embeddings_dimension = len(embeddings[0]) embeddings =", "model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def", "input text returns the embedded sequence and the sequence length. The input_text is", "text as [batch_size, text_vector_max_length, embeddings_size] :param int num_output_classes: the number of output classes", "output, gene, variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net =", "\\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'):", "targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets", "decay the learning rate :return (tf.Tensor, tf.Tensor): a tuple with the optimizer and", "None variation, variation_length = self.remove_padding(variation) # create the embeddings # first vector is", "model is built for training or not :return Dict[str,tf.Tensor]: a dict with logits", "= tf.range(batch_size) * max_length + (sequence_length - 1) output = tf.gather(sequence_output, indexes) return", "as scope: return scope def targets(self, labels, output_classes): \"\"\" Transform a vector of", "batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self, labels,", "tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings,", "of output classes :return tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1,", "and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not", "the model :param tf.Tensor global_step: the global step for training :param int learning_rate_initial:", "main class ModelSimple(object): \"\"\" Base class to create models for text classification. It", "tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout, batch_size, training) output = tf.concat([output_begin, output_end],", "text classification. It uses several layers of GRU cells. \"\"\" def model(self, input_text_begin,", "to create models for text classification. It uses several layers of GRU cells.", "= self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is not None: with", "= tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ =", "max_length + (sequence_length - 1) output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self,", ":param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is", "sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of the dynamic_rnn sequence_output = tf.reshape(sequence_output,", "loss :param tf.Tensor logits: logits output of the model :param tf.Tensor targets: targets", "training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout) cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output,", "tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of the dynamic_rnn", "embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope:", "in the dataset :param List[List[float]] embeddings: a matrix with the embeddings for the", "a dict with logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS])", "number of output classes :return tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels,", "targets = tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data): \"\"\" Calculates the", "num_layers: number of layers of the model :param float dropout: dropout value between", "is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end,", "import tensorflow.contrib.layers as layers from ..configuration import * from .text_classification_train import main class", "input_text_length - max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length", "embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) #", "gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _ =", "tf.Tensor logits: logits output of the model :param tf.Tensor targets: targets with the", "hot encoding labels :return tf.Tensor : a tensor with the loss value \"\"\"", "training) output = tf.concat([output_begin, output_end], axis=1) else: output = output_begin # full connected", "name='embeddings', dtype=tf.float32) # this means we need to add 1 to the input_text", "= tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means we need to add 1 to", ".text_classification_train import main class ModelSimple(object): \"\"\" Base class to create models for text", "embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end", "used in the dataset :param List[List[float]] embeddings: a matrix with the embeddings for", "dropout, batch_size, training) output = tf.concat([output_begin, output_end], axis=1) else: output = output_begin #", "= tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate", "int num_hidden: number of hidden GRU cells in every layer :param int num_layers:", "List[List[float]] embeddings: a matrix with the embeddings for the embedding lookup :param int", "and the input text returns the embedded sequence and the sequence length. The", "the classifier :param int batch_size: batch size, the same used in the dataset", "= tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if", "1) output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene, variation, num_output_classes,", "loss :param tf.Tensor loss: the tensor with the loss of the model :param", "matrix of one hot encoding labels :param tf.Tensor labels: an array of labels", "(sequence_length - 1) output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene,", "rate :param int learning_rate_decay: the decay of the learning rate :param int learning_rate_decay_steps:", "text classification :param tf.Tensor input_text: the input data, the text as [batch_size, text_vector_max_length,", "network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length,", "tf.nn.embedding_lookup(embeddings, input_text_end) else: embedded_sequence_end = None embedded_gene = tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene,", "tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ gene, variation = \\", "\"\"\" def model(self, input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\"", "layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None)", "whether the model is built for training or not :return Dict[str,tf.Tensor]: a dict", "# optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) # optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate)", "def loss(self, targets, graph_data): \"\"\" Calculates the softmax cross entropy loss :param tf.Tensor", "for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=dropout)", "= tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction, } def rnn(self, sequence,", "cells = [] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell", "tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__ == '__main__': main(ModelSimple(),", "batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for _ in", "learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an optimizer for the loss :param", "steps to decay the learning rate :return (tf.Tensor, tf.Tensor): a tuple with the", "length of the sequence, so the output embedded_sequence wont have the same shape", "dropout: dropout value between layers :param boolean training: whether the model is built", "sequence_length_end, \\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length,", ":return tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0)", "128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return", "the same shape as input_text or even a constant shape :param embeddings: :param", "= tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer = tf.train.RMSPropOptimizer(learning_rate) #", "the input_text mask = tf.greater_equal(input_text, 0) # true for words false for padding", "The input_text is truncated to the max length of the sequence, so the", "{ 'logits' : logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length, dropout,", "dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification :param tf.Tensor input_text: the input", "tf.concat([output_begin, output_end], axis=1) else: output = output_begin # full connected layer logits =", "num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): # calculate max length of the", "= tf.nn.embedding_lookup(embeddings, variation) embedded_variation = tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end,", "[batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin,", "sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text to max length", "[] for _ in range(num_layers): cell = tf.nn.rnn_cell.GRUCell(num_hidden) if training: cell = tf.nn.rnn_cell.DropoutWrapper(cell,", "shape :param embeddings: :param input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin)", "entropy loss :param tf.Tensor logits: logits output of the model :param tf.Tensor targets:", "learning rate :param int learning_rate_decay_steps: the number of steps to decay the learning", "int num_layers: number of layers of the model :param float dropout: dropout value", "of labels with dimension [batch_size] :param int output_classes: the total number of output", "sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is not None: with tf.variable_scope('text_end'): output_end", "activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits", "input_text_begin, input_text_end, gene, variation, num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model", "[max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation):", "return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001):", "tf.Tensor input_text: the input data, the text as [batch_size, text_vector_max_length, embeddings_size] :param int", "tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end = tf.add(input_text_end, 1) gene =", "indexes) return output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training): output =", "tf.Tensor labels: an array of labels with dimension [batch_size] :param int output_classes: the", "size, the same used in the dataset :param List[List[float]] embeddings: a matrix with", "vector used for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] +", "tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS])", "layers of the model :param float dropout: dropout value between layers :param boolean", "rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True, name='learning_rate') # optimizer optimizer", "the loss value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss)", "Transform a vector of labels into a matrix of one hot encoding labels", "variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if input_text_end is not None:", "the tensor with the loss of the model :param tf.Tensor global_step: the global", "add 1 to the input_text input_text_begin = tf.add(input_text_begin, 1) if input_text_end is not", "optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a learning rate and an", "optimizer = tf.train.GradientDescentOptimizer(learning_rate) # optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer,", "gene, variation, num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output,", "- 1) output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene, variation,", "and an optimizer for the loss :param tf.Tensor loss: the tensor with the", "(embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not None: input_text_end,", "global_step: the global step for training :param int learning_rate_initial: the initial learning rate", "[[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings, name='embeddings', dtype=tf.float32) # this means", "output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin, max_length, dropout, batch_size, training) if input_text_end is not None:", ":return tf.Tensor : a tensor with the loss value \"\"\" logits = graph_data['logits']", "activation_fn=None) return logits def remove_padding(self, input_text): # calculate max length of the input_text", "return { 'logits' : logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length,", "logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): # calculate max", "input_text: :return: (embedded_sequence, sequence_length) \"\"\" input_text_begin, sequence_length_begin = self.remove_padding(input_text_begin) if input_text_end is not", "optimizer = tf.train.AdamOptimizer(learning_rate) optimizer = optimizer.minimize(loss, global_step=global_step) return optimizer, learning_rate if __name__ ==", "a tensor with the loss value \"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets,", "\\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay,", "a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets =", "built for training or not :return Dict[str,tf.Tensor]: a dict with logits and prediction", "output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout,", "rate :param int learning_rate_decay_steps: the number of steps to decay the learning rate", "variation_length = self.remove_padding(variation) # create the embeddings # first vector is a zeros", "dict with logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if", "tf.Tensor loss: the tensor with the loss of the model :param tf.Tensor global_step:", "targets(self, labels, output_classes): \"\"\" Transform a vector of labels into a matrix of", "self.remove_padding(input_text_end) else: sequence_length_end = None variation, variation_length = self.remove_padding(variation) # create the embeddings", "slim import tensorflow.contrib.layers as layers from ..configuration import * from .text_classification_train import main", "step for training :param int learning_rate_initial: the initial learning rate :param int learning_rate_decay:", "Calculates the softmax cross entropy loss :param tf.Tensor logits: logits output of the", "\\ gene, variation = \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _", "int learning_rate_decay_steps: the number of steps to decay the learning rate :return (tf.Tensor,", "first vector is a zeros vector used for padding embeddings_dimension = len(embeddings[0]) embeddings", "= tf.concat([output, gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net,", "lookup :param int num_hidden: number of hidden GRU cells in every layer :param", "prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin, [batch_size, MAX_WORDS]) if input_text_end is not None:", "keep_prob=dropout, is_training=training) logits = layers.fully_connected(net, num_output_classes, activation_fn=None) return logits def remove_padding(self, input_text): #", "in every layer :param int num_layers: number of layers of the model :param", ": logits, 'prediction': prediction, } def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training,", "= tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32, sequence_length=sequence_length, initial_state=network.zero_state(batch_size, type)) # get last output of the", "tf.reduce_mean(embedded_variation, axis=1) return embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end, sequence_length_end, \\ embedded_gene, embedded_variation def model_arg_scope(self,", "output of the model :param tf.Tensor targets: targets with the one hot encoding", "import slim import tensorflow.contrib.layers as layers from ..configuration import * from .text_classification_train import", "tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates", "loss: the tensor with the loss of the model :param tf.Tensor global_step: the", "off_value=0.0) targets = tf.squeeze(targets, axis=1) return targets def loss(self, targets, graph_data): \"\"\" Calculates", "= tf.add(input_text_begin, 1) if input_text_end is not None: input_text_end = tf.add(input_text_end, 1) gene", "* max_length, num_hidden]) indexes = tf.range(batch_size) * max_length + (sequence_length - 1) output", "model :param tf.Tensor global_step: the global step for training :param int learning_rate_initial: the", "the learning rate :param int learning_rate_decay_steps: the number of steps to decay the", "number of layers of the model :param float dropout: dropout value between layers", "loss of the model :param tf.Tensor global_step: the global step for training :param", "max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent network. cells = [] for", "input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings", "rate and an optimizer for the loss :param tf.Tensor loss: the tensor with", "is truncated to the max length of the sequence, so the output embedded_sequence", "input_text_end is not None: input_text_end = tf.add(input_text_end, 1) gene = tf.add(gene, 1) variation", "embeddings, input_text_begin, input_text_end, gene, variation): \"\"\" Given the embeddings and the input text", "embeddings # first vector is a zeros vector used for padding embeddings_dimension =", "optimizer and the learning rate \"\"\" learning_rate = tf.train.exponential_decay(learning_rate_initial, global_step, learning_rate_decay_steps, learning_rate_decay, staircase=True,", "dimension [batch_size] :param int output_classes: the total number of output classes :return tf.Tensor:", "epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self, labels, output_classes): \"\"\" Transform a", "uses several layers of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end, gene, variation,", "Base class to create models for text classification. It uses several layers of", ":return Dict[str,tf.Tensor]: a dict with logits and prediction tensors \"\"\" input_text_begin = tf.reshape(input_text_begin,", "= \\ self.model_embedded_sequence(embeddings, input_text_begin, input_text_end, gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with", "output classes :return tf.Tensor: a tensorflow tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes,", "of steps to decay the learning rate :return (tf.Tensor, tf.Tensor): a tuple with", "for the classifier :param int batch_size: batch size, the same used in the", "the max length of the sequence, so the output embedded_sequence wont have the", "import * from .text_classification_train import main class ModelSimple(object): \"\"\" Base class to create", "= tf.concat([output_begin, output_end], axis=1) else: output = output_begin # full connected layer logits", "a model for text classification :param tf.Tensor input_text: the input data, the text", "same used in the dataset :param List[List[float]] embeddings: a matrix with the embeddings", "layer :param int num_layers: number of layers of the model :param float dropout:", "for text classification. It uses several layers of GRU cells. \"\"\" def model(self,", "num_output_classes, batch_size, embeddings, training=True, dropout=TC_MODEL_DROPOUT): \"\"\" Creates a model for text classification :param", "input_text_end is not None: input_text_end = tf.reshape(input_text_end, [batch_size, MAX_WORDS]) embedded_sequence_begin, sequence_length_begin, \\ embedded_sequence_end,", "dropout, training) prediction = tf.nn.softmax(logits) return { 'logits' : logits, 'prediction': prediction, }", "\"\"\" logits = graph_data['logits'] loss = tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits) return tf.reduce_mean(loss) def optimize(self, loss,", "learning rate and an optimizer for the loss :param tf.Tensor loss: the tensor", "+ (sequence_length - 1) output = tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output,", "with slim.arg_scope([slim.batch_norm], decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self, labels, output_classes):", "if input_text_end is not None: input_text_end, sequence_length_end = self.remove_padding(input_text_end) else: sequence_length_end = None", "sequence length. The input_text is truncated to the max length of the sequence,", "zeros vector used for padding embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension]", "layers :param boolean training: whether the model is built for training or not", "embeddings for the embedding lookup :param int num_hidden: number of hidden GRU cells", "gene = tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin) if", "empty_padding_lenght], axis=1) return input_text, sequence_length def model_embedded_sequence(self, embeddings, input_text_begin, input_text_end, gene, variation): \"\"\"", "= tf.gather(sequence_output, indexes) return output def model_fully_connected(self, output, gene, variation, num_output_classes, dropout, training):", "cells.append(cell) network = tf.nn.rnn_cell.MultiRNNCell(cells) type = sequence.dtype sequence_output, _ = tf.nn.dynamic_rnn(network, sequence, dtype=tf.float32,", "embedding lookup :param int num_hidden: number of hidden GRU cells in every layer", "axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training) logits =", "truncated to the max length of the sequence, so the output embedded_sequence wont", "= tf.reduce_sum(tf.cast(mask, tf.int32), 1) # truncate the input text to max length max_sequence_length", "} def rnn(self, sequence, sequence_length, max_length, dropout, batch_size, training, num_hidden=TC_MODEL_HIDDEN, num_layers=TC_MODEL_LAYERS): # Recurrent", "number of output classes for the classifier :param int batch_size: batch size, the", "as layers from ..configuration import * from .text_classification_train import main class ModelSimple(object): \"\"\"", "# first vector is a zeros vector used for padding embeddings_dimension = len(embeddings[0])", "logits=logits) return tf.reduce_mean(loss) def optimize(self, loss, global_step, learning_rate_initial=TC_LEARNING_RATE_INITIAL, learning_rate_decay=TC_LEARNING_RATE_DECAY, learning_rate_decay_steps=TC_LEARNING_RATE_DECAY_STEPS): \"\"\" Creates a", "length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length input_text,", "optimizer for the loss :param tf.Tensor loss: the tensor with the loss of", "model :param float dropout: dropout value between layers :param boolean training: whether the", "from tensorflow.contrib import slim import tensorflow.contrib.layers as layers from ..configuration import * from", "training: whether the model is built for training or not :return Dict[str,tf.Tensor]: a", "classification. It uses several layers of GRU cells. \"\"\" def model(self, input_text_begin, input_text_end,", "tf.greater_equal(input_text, 0) # true for words false for padding sequence_length = tf.reduce_sum(tf.cast(mask, tf.int32),", "tensor with the loss of the model :param tf.Tensor global_step: the global step", "1) gene = tf.add(gene, 1) variation = tf.add(variation, 1) embedded_sequence_begin = tf.nn.embedding_lookup(embeddings, input_text_begin)", "if input_text_end is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length, dropout,", "- max_sequence_length input_text, _ = tf.split(input_text, [max_sequence_length, empty_padding_lenght], axis=1) return input_text, sequence_length def", "= self.remove_padding(variation) # create the embeddings # first vector is a zeros vector", "scope def targets(self, labels, output_classes): \"\"\" Transform a vector of labels into a", "embeddings_dimension = len(embeddings[0]) embeddings = [[0.0] * embeddings_dimension] + embeddings embeddings = tf.constant(embeddings,", "with the one hot encoding labels :return tf.Tensor : a tensor with the", "= tf.nn.embedding_lookup(embeddings, gene) embedded_gene = tf.squeeze(embedded_gene, axis=1) embedded_variation = tf.nn.embedding_lookup(embeddings, variation) embedded_variation =", "output classes for the classifier :param int batch_size: batch size, the same used", "max length max_sequence_length = tf.reduce_max(sequence_length) input_text_length = tf.shape(input_text)[1] empty_padding_lenght = input_text_length - max_sequence_length", "embeddings: a matrix with the embeddings for the embedding lookup :param int num_hidden:", "= self.model_fully_connected(output, gene, variation, num_output_classes, dropout, training) prediction = tf.nn.softmax(logits) return { 'logits'", "training) if input_text_end is not None: with tf.variable_scope('text_end'): output_end = self.rnn(embedded_sequence_end, sequence_length_end, max_length,", "def remove_padding(self, input_text): # calculate max length of the input_text mask = tf.greater_equal(input_text,", "num_output_classes, dropout, training): output = layers.dropout(output, keep_prob=dropout, is_training=training) net = tf.concat([output, gene, variation],", "gene, variation], axis=1) net = layers.fully_connected(net, 128, activation_fn=tf.nn.relu) net = layers.dropout(net, keep_prob=dropout, is_training=training)", "gene, variation) _, max_length, _ = tf.unstack(tf.shape(embedded_sequence_begin)) with tf.variable_scope('text_begin'): output_begin = self.rnn(embedded_sequence_begin, sequence_length_begin,", "= output_begin # full connected layer logits = self.model_fully_connected(output, gene, variation, num_output_classes, dropout,", "tensor \"\"\" targets = tf.one_hot(labels, axis=-1, depth=output_classes, on_value=1.0, off_value=0.0) targets = tf.squeeze(targets, axis=1)", "number of hidden GRU cells in every layer :param int num_layers: number of", "ModelSimple(object): \"\"\" Base class to create models for text classification. It uses several", "decay=batch_norm_decay, epsilon=batch_norm_epsilon, activation_fn=None) as scope: return scope def targets(self, labels, output_classes): \"\"\" Transform", "logits def remove_padding(self, input_text): # calculate max length of the input_text mask =", "logits: logits output of the model :param tf.Tensor targets: targets with the one" ]
[ "print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell di Ungelify, ma prima, copia", "nome in lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\")", "{path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline =", "{nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for op in pipeline: print(\"open c0data.mpk\")", "print(\"\") print(\"\") print(f\"copia questi comandi nella shell di Ungelify, ma prima, copia il", "c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for op in pipeline:", "\"add\"] pipeline = [\"replace\"] for nome in lista_png: for op in pipeline: print(\"open", "lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"]", "c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell", "print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for op in", "path_dir = \"SG0-2.1.1/immagini_c0data\" print(\"\") print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"]", "c0data.mpk\") for nome in lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\")", "print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell di", "for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in", "nome in lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\")", "for nome in lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close", "in lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for", "[\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for nome in lista_png: for", "for nome in lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close", "in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi", "= [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for nome in lista_png:", "[\"replace\"] for nome in lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\")", "{nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell di Ungelify,", "print(f\"copia questi comandi nella shell di Ungelify, ma prima, copia il file c0data.mpk", "in lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\")", "in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for", "nella shell di Ungelify, ma prima, copia il file c0data.mpk nella directory {path_dir}\")", "questi comandi nella shell di Ungelify, ma prima, copia il file c0data.mpk nella", "print(\"\") print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\",", "print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for op in pipeline: print(\"open", "pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds: for op", "op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia", "= [\"replace\"] for nome in lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op}", "lista_png: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome", "= \"SG0-2.1.1/immagini_c0data\" print(\"\") print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline", "= [\"replace\", \"add\"] pipeline = [\"replace\"] for nome in lista_png: for op in", "= [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for", "lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for nome in", "\"SG0-2.1.1/immagini_c0data\" print(\"\") print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline =", "print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella", "print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell di Ungelify, ma", "c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi nella shell di Ungelify, ma prima,", "pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\") print(f\"copia questi comandi", "print(\"close c0data.mpk\") for nome in lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op}", "[\"replace\", \"add\"] pipeline = [\"replace\"] for nome in lista_png: for op in pipeline:", "<reponame>lgiacomazzo/SG0-ITA<filename>Programmi/script/print_comandi_c0data.py path_dir = \"SG0-2.1.1/immagini_c0data\" print(\"\") print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds =", "op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") for nome in lista_dds:", "pipeline = [\"replace\"] for nome in lista_png: for op in pipeline: print(\"open c0data.mpk\")", "comandi nella shell di Ungelify, ma prima, copia il file c0data.mpk nella directory", "for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\") print(\"\")", "print(\"\") print(f\"copia questi comandi nella shell di Ungelify, ma prima, copia il file", "lista_dds: for op in pipeline: print(\"open c0data.mpk\") print(f\"{op} {nome}\") print(\"close c0data.mpk\") print(\"exit\") print(\"\")", "print(\"\") print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"]", "[\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for nome", "print(f\"cd {path_dir}\") lista_png = [\"BG12A.png\",\"BG24A1.png\",\"BG24A3.png\",\"BG24A4.png\",\"BG24A5.png\",\"BG24E1.png\",\"BG24E4.png\",\"BG24N1.png\",\"BG24N3.png\",\"BG24N4.png\",\"BG83A3.png\",\"IBG094.png\",\"IBG099.png\",\"SG0_IBG004A.png\",\"SG0_IBG005A.png\",\"SG0_IBG005C.png\",\"SG0_IBG010A.png\",\"SG0_IBG010B.png\",\"SG0_IBG015A.png\",\"SG0_IBG019A.png\",\"SG0_IBG031A.png\",\"SG0_IBG031B.png\",\"SG0_IBG031C.png\",\"SG0_IBG031D.png\",\"SG0_IBG031E.png\",\"SG0_IBG031F.png\",\"SG0_IBG031G.png\",\"SG0_IBG034A.png\",\"SG0_IBG034B.png\",\"SG0_IBG034C.png\",\"SG0_IBG035A.png\",\"SG0_IBG048A.png\",\"SG0_IBG049A_honorifics.png\",\"SG0_IBG049B_honorifics.png\",\"SG0_IBG052A.png\",\"SG0_IBG056C.png\",\"SG0_IBG058A.png\",\"z_warning.png\"] lista_dds = [\"CLEARLIST.dds\",\"CONFIG.dds\",\"DATA01.dds\",\"EXMENU.dds\",\"EXMENU2.dds\",\"GSYSMES.dds\",\"help00.dds\",\"help01.dds\",\"MENUCHIP.dds\",\"MESWIN.dds\",\"PHONE.dds\",\"PHONE_B.dds\",\"PHONE_RINE.dds\",\"SAVEMENU.dds\",\"SYSM_SAVEMENU.dds\",\"SYSM_TIPS.dds\",\"TIPSCHIPS.dds\",\"title_chip.dds\"] #pipeline = [\"replace\", \"add\"] pipeline", "#pipeline = [\"replace\", \"add\"] pipeline = [\"replace\"] for nome in lista_png: for op" ]
[ "req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def", "file_name): response = req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb')", "ventura._hpath as hpath import os def download(url, file_name): response = req.urlopen(url) # Create", "Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url): response", "import os def download(url, file_name): response = req.urlopen(url) # Create folders if need", "urllib.request as req import ventura._hpath as hpath import os def download(url, file_name): response", "os def download(url, file_name): response = req.urlopen(url) # Create folders if need hpath.create_dir(file_name)", "= req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close()", "download(url, file_name): response = req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file =", "as hpath import os def download(url, file_name): response = req.urlopen(url) # Create folders", "folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url): response =", "def download(url, file_name): response = req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file", "hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url): response = req.urlopen(url) return response.read().decode(\"utf8\")", "req import ventura._hpath as hpath import os def download(url, file_name): response = req.urlopen(url)", "hpath import os def download(url, file_name): response = req.urlopen(url) # Create folders if", "import urllib.request as req import ventura._hpath as hpath import os def download(url, file_name):", "import ventura._hpath as hpath import os def download(url, file_name): response = req.urlopen(url) #", "as req import ventura._hpath as hpath import os def download(url, file_name): response =", "# Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url):", "need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url): response = req.urlopen(url) return", "if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read()) file.close() def get_page(url): response = req.urlopen(url)", "response = req.urlopen(url) # Create folders if need hpath.create_dir(file_name) file = open(file_name,'wb') file.write(response.read())" ]
[ ". import api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath: str =", "create(instance: Any) -> 'WrappedType': # expects an instance of an api_type Class class_", "from string import Template from typing import Any from dataclasses_json import DataClassJsonMixin from", "= None @dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData = None", "modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData", "from . import api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath: str", "f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj", "-> 'WrappedType': # expects an instance of an api_type Class class_ = type(instance)", "indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj =", "Any from dataclasses_json import DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin): name:", "class MetaData(DataClassJsonMixin): name: str = None dstPath: str = None modified: str =", "f: obj = json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing: obj =", "= None data: dict = None def to_instance(self): class_ = getattr(api_types, self.className) return", "if template_values: obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj =", "import api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath: str = None", "instance of an api_type Class class_ = type(instance) return WrappedType( class_.__qualname__, MetaData(), json.loads(instance.to_json())", "'r') as f: obj = json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing:", "open(path_, 'r') as f: obj = json.dumps(json.load(f)) if template_values: obj = Template(obj) if", "className: str = None metaData: MetaData = None data: dict = None def", "import Any from dataclasses_json import DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin):", "return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': # expects an instance of", "str = None metaData: MetaData = None data: dict = None def to_instance(self):", "= obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) ->", "'WrappedType': # expects an instance of an api_type Class class_ = type(instance) return", "data: dict = None def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def", "= None def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_):", "of an api_type Class class_ = type(instance) return WrappedType( class_.__qualname__, MetaData(), json.loads(instance.to_json()) )", "obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': # expects an instance", "error_on_missing=True): with open(path_, 'r') as f: obj = json.dumps(json.load(f)) if template_values: obj =", "@staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj = json.dumps(json.load(f))", "if error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def", "= Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj)", "@dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData = None data: dict", "@dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath: str = None modified: str", "as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r')", "def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj = json.dumps(json.load(f)) if", "None metaData: MetaData = None data: dict = None def to_instance(self): class_ =", "MetaData(DataClassJsonMixin): name: str = None dstPath: str = None modified: str = None", "class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData = None data: dict =", "from typing import Any from dataclasses_json import DataClassJsonMixin from . import api_types @dataclass", "None dstPath: str = None modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className:", "str = None modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className: str =", "dstPath: str = None modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className: str", "return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2)", "template_values: obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values)", "f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as", "from dataclasses_json import DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin): name: str", "obj = json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values)", "api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath: str = None modified:", "to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w')", "as f: obj = json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing: obj", "obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType':", "from dataclasses import dataclass import json from string import Template from typing import", "= None metaData: MetaData = None data: dict = None def to_instance(self): class_", "class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod", "Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod", "createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj = json.dumps(json.load(f)) if template_values:", "= getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as f:", "def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_,", "class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as", "dict = None def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self,", "def to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def", "str = None @dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData =", "WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': # expects an instance of an", "path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None,", "obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any)", "import json from string import Template from typing import Any from dataclasses_json import", "expects an instance of an api_type Class class_ = type(instance) return WrappedType( class_.__qualname__,", "with open(path_, 'r') as f: obj = json.dumps(json.load(f)) if template_values: obj = Template(obj)", "obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return", "getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()),", "with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True):", "None @dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData = None data:", "= None modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className: str = None", "dataclasses_json import DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin): name: str =", "DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None dstPath:", "template_values=None, error_on_missing=True): with open(path_, 'r') as f: obj = json.dumps(json.load(f)) if template_values: obj", "else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': #", "MetaData = None data: dict = None def to_instance(self): class_ = getattr(api_types, self.className)", "Template from typing import Any from dataclasses_json import DataClassJsonMixin from . import api_types", "None data: dict = None def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data))", "an instance of an api_type Class class_ = type(instance) return WrappedType( class_.__qualname__, MetaData(),", "dataclasses import dataclass import json from string import Template from typing import Any", "None modified: str = None @dataclass class WrappedType(DataClassJsonMixin): className: str = None metaData:", "= json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values) else:", "WrappedType(DataClassJsonMixin): className: str = None metaData: MetaData = None data: dict = None", "# expects an instance of an api_type Class class_ = type(instance) return WrappedType(", "import Template from typing import Any from dataclasses_json import DataClassJsonMixin from . import", "error_on_missing: obj = obj.substitute(template_values) else: obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance:", "<reponame>shawnsarwar/pyramid_analytics_python from dataclasses import dataclass import json from string import Template from typing", "json.dumps(json.load(f)) if template_values: obj = Template(obj) if error_on_missing: obj = obj.substitute(template_values) else: obj", "None def to_instance(self): class_ = getattr(api_types, self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with", "self.className) return class_.from_json(json.dumps(self.data)) def to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f,", "'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_,", "json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with open(path_, 'r') as f:", "@staticmethod def create(instance: Any) -> 'WrappedType': # expects an instance of an api_type", "to_file(self, path_): with open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_,", "obj = obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': # expects", "= obj.safe_substitute(template_values) return WrappedType.from_json(obj) @staticmethod def create(instance: Any) -> 'WrappedType': # expects an", "open(path_, 'w') as f: json.dump(json.loads(self.to_json()), f, indent=2) @staticmethod def createFromFile(path_, template_values=None, error_on_missing=True): with", "str = None dstPath: str = None modified: str = None @dataclass class", "string import Template from typing import Any from dataclasses_json import DataClassJsonMixin from .", "metaData: MetaData = None data: dict = None def to_instance(self): class_ = getattr(api_types,", "def create(instance: Any) -> 'WrappedType': # expects an instance of an api_type Class", "json from string import Template from typing import Any from dataclasses_json import DataClassJsonMixin", "name: str = None dstPath: str = None modified: str = None @dataclass", "dataclass import json from string import Template from typing import Any from dataclasses_json", "typing import Any from dataclasses_json import DataClassJsonMixin from . import api_types @dataclass class", "= None dstPath: str = None modified: str = None @dataclass class WrappedType(DataClassJsonMixin):", "import DataClassJsonMixin from . import api_types @dataclass class MetaData(DataClassJsonMixin): name: str = None", "import dataclass import json from string import Template from typing import Any from", "Any) -> 'WrappedType': # expects an instance of an api_type Class class_ =" ]
[ "all lower case characters with underscore ( _ ) as the word separator.", "with underscore ( _ ) as the word separator. The second variable should", "word separator. The third variable should use numbers, letters, and underscore, but still", "be a valid variable Python variable name. Make all three variables be strings", "( _ ) as the word separator. The second variable should use all", "equals variable2 compare if variable1 is not equal to variable3 \"\"\" def main():", "name. Make all three variables be strings that refer to IPv6 addresses. Use", "three different variables the first variable should use all lower case characters with", "use all lower case characters with underscore ( _ ) as the word", "the from future technique so that any string literals in Python2 are unicode.", "if variable1 is not equal to variable3 \"\"\" def main(): if __name__ ==", "the word separator. The second variable should use all upper case characters with", "be strings that refer to IPv6 addresses. Use the from future technique so", "unicode. compare if variable1 equals variable2 compare if variable1 is not equal to", "Python variable name. Make all three variables be strings that refer to IPv6", "variable should use numbers, letters, and underscore, but still be a valid variable", "separator. The second variable should use all upper case characters with underscore as", "underscore as the word separator. The third variable should use numbers, letters, and", "so that any string literals in Python2 are unicode. compare if variable1 equals", "that refer to IPv6 addresses. Use the from future technique so that any", "from future technique so that any string literals in Python2 are unicode. compare", "any string literals in Python2 are unicode. compare if variable1 equals variable2 compare", "letters, and underscore, but still be a valid variable Python variable name. Make", "with underscore as the word separator. The third variable should use numbers, letters,", "characters with underscore ( _ ) as the word separator. The second variable", "variable2 compare if variable1 is not equal to variable3 \"\"\" def main(): if", "variable1 equals variable2 compare if variable1 is not equal to variable3 \"\"\" def", "use all upper case characters with underscore as the word separator. The third", "that any string literals in Python2 are unicode. compare if variable1 equals variable2", "The second variable should use all upper case characters with underscore as the", "all three variables be strings that refer to IPv6 addresses. Use the from", "and underscore, but still be a valid variable Python variable name. Make all", "Create three different variables the first variable should use all lower case characters", "still be a valid variable Python variable name. Make all three variables be", "Use the from future technique so that any string literals in Python2 are", "technique so that any string literals in Python2 are unicode. compare if variable1", "characters with underscore as the word separator. The third variable should use numbers,", "case characters with underscore as the word separator. The third variable should use", "different variables the first variable should use all lower case characters with underscore", "as the word separator. The third variable should use numbers, letters, and underscore,", "variable should use all lower case characters with underscore ( _ ) as", "is not equal to variable3 \"\"\" def main(): if __name__ == '__main__': main()", "Python2 are unicode. compare if variable1 equals variable2 compare if variable1 is not", "are unicode. compare if variable1 equals variable2 compare if variable1 is not equal", "#!/usr/bin/env python \"\"\" Create three different variables the first variable should use all", "variables the first variable should use all lower case characters with underscore (", "variable should use all upper case characters with underscore as the word separator.", "future technique so that any string literals in Python2 are unicode. compare if", "literals in Python2 are unicode. compare if variable1 equals variable2 compare if variable1", "third variable should use numbers, letters, and underscore, but still be a valid", "Make all three variables be strings that refer to IPv6 addresses. Use the", "numbers, letters, and underscore, but still be a valid variable Python variable name.", "to IPv6 addresses. Use the from future technique so that any string literals", "if variable1 equals variable2 compare if variable1 is not equal to variable3 \"\"\"", "underscore ( _ ) as the word separator. The second variable should use", "compare if variable1 is not equal to variable3 \"\"\" def main(): if __name__", "python \"\"\" Create three different variables the first variable should use all lower", "second variable should use all upper case characters with underscore as the word", "The third variable should use numbers, letters, and underscore, but still be a", "lower case characters with underscore ( _ ) as the word separator. The", "should use all upper case characters with underscore as the word separator. The", "upper case characters with underscore as the word separator. The third variable should", "use numbers, letters, and underscore, but still be a valid variable Python variable", "all upper case characters with underscore as the word separator. The third variable", "three variables be strings that refer to IPv6 addresses. Use the from future", "should use numbers, letters, and underscore, but still be a valid variable Python", "refer to IPv6 addresses. Use the from future technique so that any string", ") as the word separator. The second variable should use all upper case", "in Python2 are unicode. compare if variable1 equals variable2 compare if variable1 is", "the word separator. The third variable should use numbers, letters, and underscore, but", "string literals in Python2 are unicode. compare if variable1 equals variable2 compare if", "variable name. Make all three variables be strings that refer to IPv6 addresses.", "variables be strings that refer to IPv6 addresses. Use the from future technique", "the first variable should use all lower case characters with underscore ( _", "strings that refer to IPv6 addresses. Use the from future technique so that", "variable Python variable name. Make all three variables be strings that refer to", "as the word separator. The second variable should use all upper case characters", "word separator. The second variable should use all upper case characters with underscore", "underscore, but still be a valid variable Python variable name. Make all three", "variable1 is not equal to variable3 \"\"\" def main(): if __name__ == '__main__':", "compare if variable1 equals variable2 compare if variable1 is not equal to variable3", "but still be a valid variable Python variable name. Make all three variables", "case characters with underscore ( _ ) as the word separator. The second", "should use all lower case characters with underscore ( _ ) as the", "_ ) as the word separator. The second variable should use all upper", "valid variable Python variable name. Make all three variables be strings that refer", "\"\"\" Create three different variables the first variable should use all lower case", "IPv6 addresses. Use the from future technique so that any string literals in", "addresses. Use the from future technique so that any string literals in Python2", "a valid variable Python variable name. Make all three variables be strings that", "first variable should use all lower case characters with underscore ( _ )", "separator. The third variable should use numbers, letters, and underscore, but still be" ]
[]
[ "= None if the_id is None: empty_message = \"Your cart is empty, please", "the_id = None if the_id is None: empty_message = \"Your cart is empty,", "CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save() cartitem", "customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return", "except Product.DoesNotExist: pass except: pass if request.method == 'POST': if product.quantity == 0:", "+= line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save() context", "try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method == 'POST':", "import * from .forms import CustomerPaymentForm from .models import * from Store.models.productModel import", "lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) >", "quando procedo al pagamento il carrello torna vuoto request.session['items_total'] = 0 template =", "= \"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request, template,", "from .models import * from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id =", "al pagamento il carrello torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context", "from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse import Store.views from Store.models.productModel", "totale cart.save() context = {\"cart\": cart} template = \"cart.html\" return render(request, template, context)", "for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo * quantità", "the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem", "try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id", "empty, please keep shopping\" context = {\"empty\": True, 'empty_message': empty_message} else: new_total =", "request.session['cart_id'] # prende l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id = None", "context = {\"cart\": cart} template = \"cart.html\" return render(request, template, context) def add_to_cart(request,", "new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist:", "from django.urls import reverse import Store.views from Store.models.productModel import * from .forms import", "request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk)", "form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form}) def success_payment(request): return render(request, 'success_payment.html')", "from Store.models.productModel import * from .forms import CustomerPaymentForm from .models import * from", "except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart =", "line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save() context =", "0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty'])", "> product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] # quantità", "prezzo totale cart.save() context = {\"cart\": cart} template = \"cart.html\" return render(request, template,", "form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all() for item", "if the_id is None: empty_message = \"Your cart is empty, please keep shopping\"", "{\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request, template, context) form = CustomerPaymentForm()", "item.product.quantity -= item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando", "aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il", "render, HttpResponseRedirect from django.urls import reverse import Store.views from Store.models.productModel import * from", "if request.method == 'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save()", "procedo al pagamento il carrello torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\"", "item.quantity # prezzo * quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total =", "-= item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo", "= \"cart.html\" return render(request, template, context) def add_to_cart(request, pk): try: the_id = request.session['cart_id']", "\"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request, template, context)", "'cartitem': cartitem} return render(request, template, context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form':", "CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity)", "cartitem = CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity", "* item.quantity # prezzo * quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total", "torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context = {\"empty\": True, 'form':", "user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request,", "# prezzo totale for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity #", "in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la", "form.save() cartitem = CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save()", "render(request, 'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all() for item in cartitem:", "0 template = \"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem': cartitem} return", "= CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save()", "= float(item.product.price) * item.quantity # prezzo * quantità new_total += line_total request.session['items_total'] =", "Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product", "= \"Your cart is empty, please keep shopping\" context = {\"empty\": True, 'empty_message':", "new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product =", "= cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save() context = {\"cart\": cart}", "carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return", "totale for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo *", "int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] #", "context = {\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00 # prezzo totale", "= {\"cart\": cart} template = \"cart.html\" return render(request, template, context) def add_to_cart(request, pk):", "new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save()", "= new_total # prezzo totale cart.save() context = {\"cart\": cart} template = \"cart.html\"", "cart = Cart.objects.get(id=the_id) except: the_id = None if the_id is None: empty_message =", "if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product':", "{'form': form}) else: form.save() cartitem = CartItem.objects.all() for item in cartitem: orderdetail =", "= Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try:", "= Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return", "return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if", "= Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method", "cart is empty, please keep shopping\" context = {\"empty\": True, 'empty_message': empty_message} else:", "Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il carrello torna vuoto request.session['items_total'] =", "'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else:", "new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass", "= 0 template = \"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem': cartitem}", "CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] # prende l'id del profumo cart", "remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None", "def cart_view(request): try: the_id = request.session['cart_id'] # prende l'id del profumo cart =", "Store.models.productModel import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] # prende l'id del", "if not form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all()", "HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not", "carrello torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context = {\"empty\": True,", "= request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem =", "== 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif", "cart.total = new_total # prezzo totale cart.save() context = {\"cart\": cart} template =", "quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo totale", "product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product})", "aggiunta al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty", "request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save() context = {\"cart\":", "import CustomerPaymentForm from .models import * from Store.models.productModel import CustomerOrders def cart_view(request): try:", "= Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method == 'POST': if product.quantity", "# prende l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id = None if", "cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete()", "product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] # quantità aggiunta", "return render(request, template, context) def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart", "None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method", "request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id)", "* from .forms import CustomerPaymentForm from .models import * from Store.models.productModel import CustomerOrders", "item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo * quantità new_total", "= new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except:", "0.00 # prezzo totale for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity", "CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST,", "l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id = None if the_id is", "cartitem.delete() # quando procedo al pagamento il carrello torna vuoto request.session['items_total'] = 0", "'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] # quantità aggiunta al carello del", "render(request, template, context) def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart =", "product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty =", "return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method ==", "del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\"))", "HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id)", "database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il carrello torna vuoto request.session['items_total']", "WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return", "Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\"))", "form, 'cartitem': cartitem} return render(request, template, context) form = CustomerPaymentForm() return render(request, 'payment.html',", "True, 'form': form, 'cartitem': cartitem} return render(request, template, context) form = CustomerPaymentForm() return", "{'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty", "cartitem} return render(request, template, context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form})", "Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method ==", "== 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form':", "context = {\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request, template, context) form", "return render(request, template, context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form}) def", "del profumo cart = Cart.objects.get(id=the_id) except: the_id = None if the_id is None:", "CustomerPaymentForm from .models import * from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id", "except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def", "product}) else: qty = request.POST['qty'] # quantità aggiunta al carello del singolo profumo", "orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità nel", "= 0.00 # prezzo totale for item in cart.cartitem_set.all(): line_total = float(item.product.price) *", "vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context = {\"empty\": True, 'form': form,", "= {\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00 # prezzo totale for", "# aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento", "* from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] # prende", "Cart.objects.get(id=the_id) except: the_id = None if the_id is None: empty_message = \"Your cart", "template, context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form}) def success_payment(request): return", "return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart =", "profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\"))", "new_total = 0.00 # prezzo totale for item in cart.cartitem_set.all(): line_total = float(item.product.price)", "elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty']", "product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method == 'POST': if", "= CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form =", "pass except: pass if request.method == 'POST': if product.quantity == 0: lista_attesa =", "render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product': product})", "HttpResponseRedirect from django.urls import reverse import Store.views from Store.models.productModel import * from .forms", "cart.cartitem_set.count() cart.total = new_total # prezzo totale cart.save() context = {\"cart\": cart} template", "except: the_id = None if the_id is None: empty_message = \"Your cart is", "return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except:", "try: the_id = request.session['cart_id'] # prende l'id del profumo cart = Cart.objects.get(id=the_id) except:", "= qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id =", "cart_view(request): try: the_id = request.session['cart_id'] # prende l'id del profumo cart = Cart.objects.get(id=the_id)", "form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form': form}) else:", "is empty, please keep shopping\" context = {\"empty\": True, 'empty_message': empty_message} else: new_total", "if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request,", "form}) else: form.save() cartitem = CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user,", "request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart", "line_total = float(item.product.price) * item.quantity # prezzo * quantità new_total += line_total request.session['items_total']", "= CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -=", "'empty_message': empty_message} else: new_total = 0.00 # prezzo totale for item in cart.cartitem_set.all():", "id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return", "cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità", ".forms import CustomerPaymentForm from .models import * from Store.models.productModel import CustomerOrders def cart_view(request):", "instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save() cartitem =", "render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] # quantità aggiunta al carello", "'form': form, 'cartitem': cartitem} return render(request, template, context) form = CustomerPaymentForm() return render(request,", "from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] # prende l'id", "prezzo totale for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo", "try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\"))", "cart} template = \"cart.html\" return render(request, template, context) def add_to_cart(request, pk): try: the_id", "except: pass if request.method == 'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product,", "django.urls import reverse import Store.views from Store.models.productModel import * from .forms import CustomerPaymentForm", "= request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id", "'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all() for item in cartitem: orderdetail", "empty_message} else: new_total = 0.00 # prezzo totale for item in cart.cartitem_set.all(): line_total", "request.session['items_total'] = 0 template = \"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem':", "= request.POST['qty'] # quantità aggiunta al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart,", "cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id", "profumo cart = Cart.objects.get(id=the_id) except: the_id = None if the_id is None: empty_message", "orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() #", "return render(request, 'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all() for item in", "{'product': product}) else: qty = request.POST['qty'] # quantità aggiunta al carello del singolo", "def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id =", "import Store.views from Store.models.productModel import * from .forms import CustomerPaymentForm from .models import", "== 'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request,", "qty = request.POST['qty'] # quantità aggiunta al carello del singolo profumo cart_item =", "template = \"cart.html\" return render(request, template, context) def add_to_cart(request, pk): try: the_id =", "context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form}) def success_payment(request): return render(request,", "None: empty_message = \"Your cart is empty, please keep shopping\" context = {\"empty\":", "def customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid():", "nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il carrello torna vuoto", "* quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total # prezzo", "request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html',", "keep shopping\" context = {\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00 #", "product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try:", "cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart", "singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return", "pk): try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id", "new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id)", "# quando procedo al pagamento il carrello torna vuoto request.session['items_total'] = 0 template", "True, 'empty_message': empty_message} else: new_total = 0.00 # prezzo totale for item in", "{\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00 # prezzo totale for item", "render(request, template, context) form = CustomerPaymentForm() return render(request, 'payment.html', {'form': form}) def success_payment(request):", "quantità aggiunta al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity =", "= Cart.objects.get(id=the_id) except: the_id = None if the_id is None: empty_message = \"Your", "product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete()", "float(item.product.price) * item.quantity # prezzo * quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count()", "cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form = CustomerPaymentForm(request.POST, instance=request.user)", "CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity", "= WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity:", "return render(request, 'finished_perfumes.html', {'product': product}) else: qty = request.POST['qty'] # quantità aggiunta al", "= request.session['cart_id'] # prende l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id =", "import reverse import Store.views from Store.models.productModel import * from .forms import CustomerPaymentForm from", "= CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request,", "quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il carrello torna", "Store.models.productModel import * from .forms import CustomerPaymentForm from .models import * from Store.models.productModel", "in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo * quantità new_total +=", "HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST':", "template, context) def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart = Cart()", "the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass", "not form.is_valid(): return render(request, 'payment.html', {'form': form}) else: form.save() cartitem = CartItem.objects.all() for", "new_total # prezzo totale cart.save() context = {\"cart\": cart} template = \"cart.html\" return", ".models import * from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id']", "# prezzo totale cart.save() context = {\"cart\": cart} template = \"cart.html\" return render(request,", "cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if request.method == 'POST': form", "prezzo * quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total #", "= CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno la quantità nel database", "import * from Store.models.productModel import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] #", "context) def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save()", "django.shortcuts import render, HttpResponseRedirect from django.urls import reverse import Store.views from Store.models.productModel import", "HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id", "else: new_total = 0.00 # prezzo totale for item in cart.cartitem_set.all(): line_total =", "\"Your cart is empty, please keep shopping\" context = {\"empty\": True, 'empty_message': empty_message}", "CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id):", "qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def remove_from_cart(request, id): try: the_id = request.session['cart_id']", "the_id = request.session['cart_id'] # prende l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id", "cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if", "= None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request): if", "import render, HttpResponseRedirect from django.urls import reverse import Store.views from Store.models.productModel import *", "prende l'id del profumo cart = Cart.objects.get(id=the_id) except: the_id = None if the_id", "Product.DoesNotExist: pass except: pass if request.method == 'POST': if product.quantity == 0: lista_attesa", "else: qty = request.POST['qty'] # quantità aggiunta al carello del singolo profumo cart_item", "reverse import Store.views from Store.models.productModel import * from .forms import CustomerPaymentForm from .models", "cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save() return HttpResponseRedirect(reverse(\"carts:cart_view\")) return HttpResponseRedirect(reverse(\"carts:cart_view\")) def", "shopping\" context = {\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00 # prezzo", "# quantità aggiunta al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity", "'POST': form = CustomerPaymentForm(request.POST, instance=request.user) if not form.is_valid(): return render(request, 'payment.html', {'form': form})", "template = \"success_payment.html\" context = {\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request,", "il carrello torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context = {\"empty\":", "= {\"empty\": True, 'form': form, 'cartitem': cartitem} return render(request, template, context) form =", "pass if request.method == 'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user)", "item.quantity # aggiorno la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al", "please keep shopping\" context = {\"empty\": True, 'empty_message': empty_message} else: new_total = 0.00", "def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id']", "request.POST['qty'] # quantità aggiunta al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product)", "{\"cart\": cart} template = \"cart.html\" return render(request, template, context) def add_to_cart(request, pk): try:", "return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html', {'product':", "= new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=pk) except", "item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity # aggiorno", "'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return render(request, 'finished_perfumes.html',", "None if the_id is None: empty_message = \"Your cart is empty, please keep", "empty_message = \"Your cart is empty, please keep shopping\" context = {\"empty\": True,", "\"cart.html\" return render(request, template, context) def add_to_cart(request, pk): try: the_id = request.session['cart_id'] except:", "the_id = None return HttpResponseRedirect(reverse(\"carts:cart_view\")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse(\"carts:cart_view\")) def customer_payment(request):", "import CustomerOrders def cart_view(request): try: the_id = request.session['cart_id'] # prende l'id del profumo", "the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id =", "for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product) orderdetail.save() item.product.quantity -= item.quantity #", "la quantità nel database Product.objects.filter(id=item.product.pk).update(quantity=item.product.quantity) cartitem.delete() # quando procedo al pagamento il carrello", "Store.views from Store.models.productModel import * from .forms import CustomerPaymentForm from .models import *", "from .forms import CustomerPaymentForm from .models import * from Store.models.productModel import CustomerOrders def", "cart.save() context = {\"cart\": cart} template = \"cart.html\" return render(request, template, context) def", "add_to_cart(request, pk): try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] =", "request.method == 'POST': if product.quantity == 0: lista_attesa = WaitingListModel.objects.create(product=product, user=request.user) lista_attesa.save() return", "lista_attesa.save() return render(request, 'finished_perfumes.html', {'product': product}) elif int(request.POST['qty']) > product.quantity: return render(request, 'finished_perfumes.html',", "the_id is None: empty_message = \"Your cart is empty, please keep shopping\" context", "cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity # prezzo * quantità new_total += line_total", "is None: empty_message = \"Your cart is empty, please keep shopping\" context =", "# prezzo * quantità new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total", "al carello del singolo profumo cart_item = CartItem.objects.create(cart=cart, product=product) cart_item.quantity = qty cart_item.save()", "else: form.save() cartitem = CartItem.objects.all() for item in cartitem: orderdetail = CustomerOrders(user=request.user, product=item.product)", "pagamento il carrello torna vuoto request.session['items_total'] = 0 template = \"success_payment.html\" context =", "Product.objects.get(id=pk) except Product.DoesNotExist: pass except: pass if request.method == 'POST': if product.quantity ==" ]
[ "def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # #", "= lista # print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista =", "for v in args: # print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) #", "# print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade", "# print(args) # print(args[0]) # print(args[-1]) # acessa o ultimo item da lista", "acessa o ultimo item da lista # print(len(args)) # for v in args:", "idade = kwargs.get('idade') if idade is not None: print(idade) else: print('idade nao existe')", "= kwargs.get('idade') if idade is not None: print(idade) else: print('idade nao existe') #", "*args e **kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) #", "# print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2", "print(nome) idade = kwargs.get('idade') if idade is not None: print(idade) else: print('idade nao", "nomeados, basicamente um json def func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1])", "idade is not None: print(idade) else: print('idade nao existe') # lista = [1,2,3,4,5]", "- *args e **kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6)", "# def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 #", "lista # print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5]", "print(args) # print(args[0]) # print(args[-1]) # acessa o ultimo item da lista #", "# var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs = key", "in args: # print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome", "a6 # # # var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) #", "func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # # #", "ultimo item da lista # print(len(args)) # for v in args: # print(v)", "existe') # lista = [1,2,3,4,5] # n1, n2, *n = lista # print(n1,", "# print(len(args)) # for v in args: # print(v) # print(args[0]) print(args) print(kwargs)", "# for v in args: # print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome'])", "key word args - argumentos nomeados, basicamente um json def func(*args, **kwargs): #", "# print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # # # var = func(1,2,3,4,5,", "# print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 = [10,20,30,40,50] func(*lista, *lista2,", "# # # var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs", "nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is not None: print(idade)", "um json def func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1]) # acessa", "# acessa o ultimo item da lista # print(len(args)) # for v in", "nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs = key word args - argumentos", "var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs = key word", "# print(args[0]) # print(args[-1]) # acessa o ultimo item da lista # print(len(args))", "a6) # return nome, a6 # # # var = func(1,2,3,4,5, nome='lincoln', a6='5')", "*n = lista # print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista", "basicamente um json def func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1]) #", "**kwargs = key word args - argumentos nomeados, basicamente um json def func(*args,", "print(var[0], var[1]) # **kwargs = key word args - argumentos nomeados, basicamente um", "nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # # # var", "# print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is not", "funcoes - *args e **kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome,", "None: print(idade) else: print('idade nao existe') # lista = [1,2,3,4,5] # n1, n2,", "print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome)", "item da lista # print(len(args)) # for v in args: # print(v) #", "json def func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1]) # acessa o", "nao existe') # lista = [1,2,3,4,5] # n1, n2, *n = lista #", "n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 = [10,20,30,40,50]", "**kwargs): # print(args) # print(args[0]) # print(args[-1]) # acessa o ultimo item da", "if idade is not None: print(idade) else: print('idade nao existe') # lista =", "args - argumentos nomeados, basicamente um json def func(*args, **kwargs): # print(args) #", "print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # # # var = func(1,2,3,4,5, nome='lincoln',", "# print(var[0], var[1]) # **kwargs = key word args - argumentos nomeados, basicamente", "da lista # print(len(args)) # for v in args: # print(v) # print(args[0])", "nome, a6 # # # var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1])", "else: print('idade nao existe') # lista = [1,2,3,4,5] # n1, n2, *n =", "func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1]) # acessa o ultimo item", "print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is not None:", "[1,2,3,4,5] # n1, n2, *n = lista # print(n1, n2, n) # print(*lista,", "= key word args - argumentos nomeados, basicamente um json def func(*args, **kwargs):", "- argumentos nomeados, basicamente um json def func(*args, **kwargs): # print(args) # print(args[0])", "print(args[-1]) # acessa o ultimo item da lista # print(len(args)) # for v", "# **kwargs = key word args - argumentos nomeados, basicamente um json def", "= [1,2,3,4,5] # n1, n2, *n = lista # print(n1, n2, n) #", "def func(*args, **kwargs): # print(args) # print(args[0]) # print(args[-1]) # acessa o ultimo", "print(args[0]) # print(args[-1]) # acessa o ultimo item da lista # print(len(args)) #", "# print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome')", "lista = [1,2,3,4,5] # n1, n2, *n = lista # print(n1, n2, n)", "= func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs = key word args", "= kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is not None: print(idade) else:", "n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 = [10,20,30,40,50] func(*lista,", "print(idade) else: print('idade nao existe') # lista = [1,2,3,4,5] # n1, n2, *n", "# print(args[-1]) # acessa o ultimo item da lista # print(len(args)) # for", "# # var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs =", "print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade')", "# n1, n2, *n = lista # print(n1, n2, n) # print(*lista, sep='\\n')", "print(len(args)) # for v in args: # print(v) # print(args[0]) print(args) print(kwargs) #", "n2, *n = lista # print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6)", "kwargs.get('idade') if idade is not None: print(idade) else: print('idade nao existe') # lista", "# return nome, a6 # # # var = func(1,2,3,4,5, nome='lincoln', a6='5') #", "print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 = [10,20,30,40,50] func(*lista, *lista2, nome='lincoln',", "a6='5') # print(var[0], var[1]) # **kwargs = key word args - argumentos nomeados,", "print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if", "print('idade nao existe') # lista = [1,2,3,4,5] # n1, n2, *n = lista", "o ultimo item da lista # print(len(args)) # for v in args: #", "sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 = [10,20,30,40,50] func(*lista, *lista2, nome='lincoln', sobrenome='ruteski')", "n1, n2, *n = lista # print(n1, n2, n) # print(*lista, sep='\\n') #", "var[1]) # **kwargs = key word args - argumentos nomeados, basicamente um json", "not None: print(idade) else: print('idade nao existe') # lista = [1,2,3,4,5] # n1,", "\"\"\" funcoes - *args e **kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): #", "args: # print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome =", "is not None: print(idade) else: print('idade nao existe') # lista = [1,2,3,4,5] #", "e **kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return", "func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0], var[1]) # **kwargs = key word args -", "# lista = [1,2,3,4,5] # n1, n2, *n = lista # print(n1, n2,", "\"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6", "print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade =", "lista # print(len(args)) # for v in args: # print(v) # print(args[0]) print(args)", "argumentos nomeados, basicamente um json def func(*args, **kwargs): # print(args) # print(args[0]) #", "# print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade", "v in args: # print(v) # print(args[0]) print(args) print(kwargs) # print(kwargs['nome']) # print(kwargs['sobrenome'])", "a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome, a6 # # # var =", "print(kwargs['nome']) # print(kwargs['sobrenome']) nome = kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is", "print(n1, n2, n) # print(*lista, sep='\\n') # func(1,2,3,4,5,6) lista = [1,2,3,4,5] lista2 =", "**kwargs \"\"\" # def func(a1,a2,a3,a4,a5, nome=None, a6=None): # print(a1,a2,a3,a4,a5,nome, a6) # return nome,", "return nome, a6 # # # var = func(1,2,3,4,5, nome='lincoln', a6='5') # print(var[0],", "kwargs.get('nome') print(nome) idade = kwargs.get('idade') if idade is not None: print(idade) else: print('idade", "word args - argumentos nomeados, basicamente um json def func(*args, **kwargs): # print(args)" ]
[ "import silhouette_score, calinski_harabaz_score def get_silhouette_coefficient(cluster_train_data,labels_assigned): return silhouette_score(cluster_train_data,labels_assigned) def get_calinski_harabaz_coefficient(cluster_train_data, labels_assigned): return calinski_harabaz_score(cluster_train_data, labels_assigned)", "<reponame>opennlp/DeepPhrase<filename>clusterwrapper/clustermetrics.py from sklearn.metrics import silhouette_score, calinski_harabaz_score def get_silhouette_coefficient(cluster_train_data,labels_assigned): return silhouette_score(cluster_train_data,labels_assigned) def get_calinski_harabaz_coefficient(cluster_train_data, labels_assigned):", "from sklearn.metrics import silhouette_score, calinski_harabaz_score def get_silhouette_coefficient(cluster_train_data,labels_assigned): return silhouette_score(cluster_train_data,labels_assigned) def get_calinski_harabaz_coefficient(cluster_train_data, labels_assigned): return", "sklearn.metrics import silhouette_score, calinski_harabaz_score def get_silhouette_coefficient(cluster_train_data,labels_assigned): return silhouette_score(cluster_train_data,labels_assigned) def get_calinski_harabaz_coefficient(cluster_train_data, labels_assigned): return calinski_harabaz_score(cluster_train_data," ]
[ "items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items: text= \"WELCOME\" if", "i in items: text= \"WELCOME\" if i == x else '.|.'*i print (text.center(y,'-'))", "list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items: text= \"WELCOME\" if i ==", "output to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for", "STDIN. Print output to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items =", "= map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items: text=", "map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items: text= \"WELCOME\"", "= items+items[::-1][1:] for i in items: text= \"WELCOME\" if i == x else", "<gh_stars>0 # Enter your code here. Read input from STDIN. Print output to", "STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i in", "your code here. Read input from STDIN. Print output to STDOUT x,y =", "Read input from STDIN. Print output to STDOUT x,y = map(int,input().split()) items =", "= list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items: text= \"WELCOME\" if i", "Print output to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:]", "Enter your code here. Read input from STDIN. Print output to STDOUT x,y", "from STDIN. Print output to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items", "x,y = map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i in items:", "items+items[::-1][1:] for i in items: text= \"WELCOME\" if i == x else '.|.'*i", "for i in items: text= \"WELCOME\" if i == x else '.|.'*i print", "input from STDIN. Print output to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2))", "code here. Read input from STDIN. Print output to STDOUT x,y = map(int,input().split())", "here. Read input from STDIN. Print output to STDOUT x,y = map(int,input().split()) items", "to STDOUT x,y = map(int,input().split()) items = list(range(1,x+1,2)) items = items+items[::-1][1:] for i", "items = items+items[::-1][1:] for i in items: text= \"WELCOME\" if i == x", "# Enter your code here. Read input from STDIN. Print output to STDOUT" ]
[ "= self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/')", "view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif", "to redirect user to login unless they have a valid APIC Cookie class", "def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args,", "get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def", "<filename>deployment_tool/middleware.py import re from django.shortcuts import render, redirect from django.conf import settings EXEMPT_URL", "redirect user to login unless they have a valid APIC Cookie class LoginRequiredMiddleware:", "# Class to redirect user to login unless they have a valid APIC", "user to login unless they have a valid APIC Cookie class LoginRequiredMiddleware: def", "def process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path", "import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user to login unless", "= settings.LOGIN_URL.lstrip('/') # Class to redirect user to login unless they have a", "re from django.shortcuts import render, redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/')", "self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self,", "import render, redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to", "return response def process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE')", "they have a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response =", "settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user to login unless they", "to login unless they have a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self,", "from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user to", "from django.shortcuts import render, redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') #", "settings.LOGIN_URL.lstrip('/') # Class to redirect user to login unless they have a valid", "__init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response", "EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL: return None else: return", "redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user", "view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL)", "request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path", "django.shortcuts import render, redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class", "view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return", "get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func,", "login unless they have a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response):", "request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL:", "request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL:", "unless they have a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response", "if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in", "= get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request,", "in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL: return None else:", "Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response", "response def process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and", "= request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or", "request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): path", "path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL: return None", "process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in", "django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user to login", "EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect user to login unless they have", "path = request.path_info.lstrip('/') if request.session.has_key('APIC_COOKIE') and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE')", "APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request):", "valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self,", "and path in EXEMPT_URL: return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL: return", "LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request)", "response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): path =", "return redirect(settings.LOGIN_REDIRECT_URL) elif request.session.has_key('APIC_COOKIE') or path in EXEMPT_URL: return None else: return redirect(settings.LOGIN_URL)", "def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return", "__call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs):", "a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def", "class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response =", "self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): path = request.path_info.lstrip('/') if", "import re from django.shortcuts import render, redirect from django.conf import settings EXEMPT_URL =", "render, redirect from django.conf import settings EXEMPT_URL = settings.LOGIN_URL.lstrip('/') # Class to redirect", "Class to redirect user to login unless they have a valid APIC Cookie", "have a valid APIC Cookie class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response" ]
[]
[ "is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce',", "nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig =", "@weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self):", "func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp =", "self.config = weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str", "'signature']) nonce, timestamp, sig = nts token = req.config.token if is_valid_request(token, nonce, timestamp,", "_wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig", "['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts token = req.config.token if is_valid_request(token,", "..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k,", "self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body) or \"\"", "def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml", "set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async", "echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body)", "map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts token", "if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize()", "compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\")", "weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature'])", "self.weapp = weapp self.config = weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only", "= weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str =", "# encoding=utf-8 import functools import tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func)", "return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config", "def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config = weapp.config", "is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class", "self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body) or \"\" self.write(xml) return WeixinRequestHandler", "= nts token = req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403)", "token = req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_", "return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp", "req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts token = req.config.token", "\"\") self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body) or \"\" self.write(xml) return", "def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp',", "= weapp self.config = weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def", "k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts token =", "timestamp, sig = nts token = req.config.token if is_valid_request(token, nonce, timestamp, sig): return", "make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config = weapp.config def", "initialize(self): self.weapp = weapp self.config = weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server')", "weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument", "('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body) or \"\" self.write(xml)", "_wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config =", "self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def", "req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp", "def initialize(self): self.weapp = weapp self.config = weapp.config def compute_etag(self): return def set_default_headers(self):", "import functools import tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req):", "nts token = req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return", "return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str)", "<gh_stars>1-10 # encoding=utf-8 import functools import tornado.web from ..utils import is_valid_request def weixin_request_only(func):", "weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config = weapp.config def compute_etag(self):", "tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda", "def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr',", "timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def", "get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml =", "@functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce,", "from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k:", "def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp,", "class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config = weapp.config def compute_etag(self): return", "encoding=utf-8 import functools import tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def", "functools import tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts", "import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts = map(lambda k: req.get_query_argument(k, \"\"),", "= map(lambda k: req.get_query_argument(k, \"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts", "\"\"), ['nonce', 'timestamp', 'signature']) nonce, timestamp, sig = nts token = req.config.token if", "sig = nts token = req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req)", "weapp self.config = weapp.config def compute_etag(self): return def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self):", "'timestamp', 'signature']) nonce, timestamp, sig = nts token = req.config.token if is_valid_request(token, nonce,", "def set_default_headers(self): self.clear_header('Server') @weixin_request_only def get(self): echo_str = self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only", "= req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def", "nonce, timestamp, sig = nts token = req.config.token if is_valid_request(token, nonce, timestamp, sig):", "nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler):", "sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp): weapp.initialize() class WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self):", "WeixinRequestHandler(tornado.web.RequestHandler): def initialize(self): self.weapp = weapp self.config = weapp.config def compute_etag(self): return def", "import tornado.web from ..utils import is_valid_request def weixin_request_only(func): @functools.wraps(func) def _wrapper_(req): nts =", "req.config.token if is_valid_request(token, nonce, timestamp, sig): return func(req) req.set_status(403) return _wrapper_ def make_handler(weapp):", "= self.get_argument ('echostr', \"\") self.finish(echo_str) @weixin_request_only async def post(self): xml = self.weapp.reply(self.request.body) or" ]
[ "search is starting @type start_cb: callable @param end_cb: Function to call when the", "@param found_cb: Function to call when text is found in an item @type", "= move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors here, we might need", "if test_cb(curr, text): found_cb(curr) end_cb() return True # seek in desired direction try:", "start_cb() try: if not current: curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore", "defined by the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb,", "seek in desired direction try: curr = move_cb(curr) except (ValueError, AttributeError): break end_cb()", "@type test_cb: callable @param found_cb: Function to call when text is found in", "to perform a circular search through a body of items. How the search", "any errors here, we might need to wrap pass else: while 1: if", "else: while 1: if test_cb(curr, text): found_cb(curr) end_cb() return False # seek in", "False # seek in desired direction try: curr = move_cb(curr) except ValueError: break", "AttributeError: end_cb() return None try: # reset to endpoint curr = reset_cb(curr) except", "text): found_cb(curr) end_cb() return False # seek in desired direction try: curr =", "is starting @type start_cb: callable @param end_cb: Function to call when the search", "AttributeError): end_cb() return None while 1: if test_cb(curr, text): found_cb(curr) end_cb() return True", "in desired direction try: curr = move_cb(curr) except (ValueError, AttributeError): break end_cb() return", "items. How the search proceeds is entirely defined by the callbacks. ''' def", "and the accompanying materials are made available under the terms of The BSD", "is entirely defined by the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb,", "the terms of The BSD License which accompanies this distribution, and is available", "text is found in an item @type found_cb: callable @param reset_cb: Function to", "program and the accompanying materials are made available under the terms of The", "is ending @type end_cb: callable @param move_cb: Function to call to move to", "made available under the terms of The BSD License which accompanies this distribution,", "CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method for performing", "None try: # reset to endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb()", "@param current: Start the search on the current item? @type current: boolean @return:", "an item @type found_cb: callable @param reset_cb: Function to call when wrapping during", "string @param current: Start the search on the current item? @type current: boolean", "False if not wrapped, None if not found @rtype: boolean ''' # set", "found @rtype: boolean ''' # set to first item to test curr =", "to test if an item contains the text @type test_cb: callable @param found_cb:", "callable @param move_cb: Function to call to move to another item to test", "@type end_cb: callable @param move_cb: Function to call to move to another item", "when text is found in an item @type found_cb: callable @param reset_cb: Function", "errors here, we might need to wrap pass else: while 1: if test_cb(curr,", "@rtype: boolean ''' # set to first item to test curr = start_cb()", "found_cb, reset_cb, text, current): ''' Method for performing a generic, wrapping search over", "seek in desired direction try: curr = move_cb(curr) except ValueError: break except AttributeError:", "call to move to another item to test @type move_cb: callable @param test_cb:", "try: # reset to endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return", "return True # seek in desired direction try: curr = move_cb(curr) except (ValueError,", "method using callbacks to perform a circular search through a body of items.", "text: Text to locate @type text: string @param current: Start the search on", "available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a generic method using", "current: boolean @return: True if wrapped, False if not wrapped, None if not", "current item? @type current: boolean @return: True if wrapped, False if not wrapped,", "@param end_cb: Function to call when the search is ending @type end_cb: callable", "<<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD License All rights reserved. This", "This program and the accompanying materials are made available under the terms of", "if not current: curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors", "accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing", "to test curr = start_cb() try: if not current: curr = move_cb(start_cb()) except", "reset to endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while", "@type reset_cb: callable @param text: Text to locate @type text: string @param current:", "which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): '''", "ValueError: break except AttributeError: end_cb() return None try: # reset to endpoint curr", "Defines search related mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license:", "text, current): ''' Method for performing a generic, wrapping search over an entire", "terms of The BSD License which accompanies this distribution, and is available at", "CircularSearchMixin(object): ''' Mixing providing a generic method using callbacks to perform a circular", "test curr = start_cb() try: if not current: curr = move_cb(start_cb()) except (ValueError,", "True if wrapped, False if not wrapped, None if not found @rtype: boolean", "performing a generic, wrapping search over an entire collection. @param start_cb: Function to", "related mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD License", "except (ValueError, AttributeError): # ignore any errors here, we might need to wrap", "when wrapping during search @type reset_cb: callable @param text: Text to locate @type", "found_cb(curr) end_cb() return False # seek in desired direction try: curr = move_cb(curr)", "@param reset_cb: Function to call when wrapping during search @type reset_cb: callable @param", "test_cb, found_cb, reset_cb, text, current): ''' Method for performing a generic, wrapping search", "call when the search is starting @type start_cb: callable @param end_cb: Function to", "under the terms of The BSD License which accompanies this distribution, and is", "search through a body of items. How the search proceeds is entirely defined", "License which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object):", "ending @type end_cb: callable @param move_cb: Function to call to move to another", "distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a", "''' Defines search related mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME>", "callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): '''", "when the search is starting @type start_cb: callable @param end_cb: Function to call", "item? @type current: boolean @return: True if wrapped, False if not wrapped, None", "text): found_cb(curr) end_cb() return True # seek in desired direction try: curr =", "providing a generic method using callbacks to perform a circular search through a", "move_cb: callable @param test_cb: Function to call to test if an item contains", "wrapping search over an entire collection. @param start_cb: Function to call when the", "try: if not current: curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore any", "# reset to endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return None", "using callbacks to perform a circular search through a body of items. How", "move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method for performing a generic, wrapping", "All rights reserved. This program and the accompanying materials are made available under", "during search @type reset_cb: callable @param text: Text to locate @type text: string", "end_cb: callable @param move_cb: Function to call to move to another item to", "this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing", "<NAME> @license: BSD License All rights reserved. This program and the accompanying materials", "an entire collection. @param start_cb: Function to call when the search is starting", "the search on the current item? @type current: boolean @return: True if wrapped,", "call when text is found in an item @type found_cb: callable @param reset_cb:", "in an item @type found_cb: callable @param reset_cb: Function to call when wrapping", "the search proceeds is entirely defined by the callbacks. ''' def CircularSearch(self, start_cb,", "reset_cb, text, current): ''' Method for performing a generic, wrapping search over an", "Function to call to move to another item to test @type move_cb: callable", "curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors here, we might", "wrapping during search @type reset_cb: callable @param text: Text to locate @type text:", "item to test @type move_cb: callable @param test_cb: Function to call to test", "call when the search is ending @type end_cb: callable @param move_cb: Function to", "test_cb: callable @param found_cb: Function to call when text is found in an", "item to test curr = start_cb() try: if not current: curr = move_cb(start_cb())", "@return: True if wrapped, False if not wrapped, None if not found @rtype:", "if not found @rtype: boolean ''' # set to first item to test", "item @type found_cb: callable @param reset_cb: Function to call when wrapping during search", "while 1: if test_cb(curr, text): found_cb(curr) end_cb() return True # seek in desired", "if wrapped, False if not wrapped, None if not found @rtype: boolean '''", "move_cb: Function to call to move to another item to test @type move_cb:", "<filename>Mixin/Search.py<gh_stars>1-10 ''' Defines search related mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008", "License All rights reserved. This program and the accompanying materials are made available", "= reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while 1: if test_cb(curr, text):", "curr = start_cb() try: if not current: curr = move_cb(start_cb()) except (ValueError, AttributeError):", "end_cb() return False # seek in desired direction try: curr = move_cb(curr) except", "to endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while 1:", "might need to wrap pass else: while 1: if test_cb(curr, text): found_cb(curr) end_cb()", "available under the terms of The BSD License which accompanies this distribution, and", "(ValueError, AttributeError): end_cb() return None while 1: if test_cb(curr, text): found_cb(curr) end_cb() return", "body of items. How the search proceeds is entirely defined by the callbacks.", "@type found_cb: callable @param reset_cb: Function to call when wrapping during search @type", "Function to call when the search is ending @type end_cb: callable @param move_cb:", "search proceeds is entirely defined by the callbacks. ''' def CircularSearch(self, start_cb, end_cb,", "Start the search on the current item? @type current: boolean @return: True if", "reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while 1: if test_cb(curr, text): found_cb(curr)", "generic method using callbacks to perform a circular search through a body of", "Function to call to test if an item contains the text @type test_cb:", "mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD License All", "@type move_cb: callable @param test_cb: Function to call to test if an item", "reset_cb: Function to call when wrapping during search @type reset_cb: callable @param text:", "text: string @param current: Start the search on the current item? @type current:", "move to another item to test @type move_cb: callable @param test_cb: Function to", "in desired direction try: curr = move_cb(curr) except ValueError: break except AttributeError: end_cb()", "entire collection. @param start_cb: Function to call when the search is starting @type", "found_cb(curr) end_cb() return True # seek in desired direction try: curr = move_cb(curr)", "generic, wrapping search over an entire collection. @param start_cb: Function to call when", "# seek in desired direction try: curr = move_cb(curr) except ValueError: break except", "search on the current item? @type current: boolean @return: True if wrapped, False", "ignore any errors here, we might need to wrap pass else: while 1:", "starting @type start_cb: callable @param end_cb: Function to call when the search is", "if not wrapped, None if not found @rtype: boolean ''' # set to", "wrapped, None if not found @rtype: boolean ''' # set to first item", "@copyright: Copyright (c) 2008 <NAME> @license: BSD License All rights reserved. This program", "to first item to test curr = start_cb() try: if not current: curr", "None if not found @rtype: boolean ''' # set to first item to", "while 1: if test_cb(curr, text): found_cb(curr) end_cb() return False # seek in desired", "endpoint curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while 1: if", "materials are made available under the terms of The BSD License which accompanies", "end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method for performing a generic,", "to call when the search is starting @type start_cb: callable @param end_cb: Function", "to call when the search is ending @type end_cb: callable @param move_cb: Function", "reserved. This program and the accompanying materials are made available under the terms", "end_cb: Function to call when the search is ending @type end_cb: callable @param", "callable @param reset_cb: Function to call when wrapping during search @type reset_cb: callable", "except AttributeError: end_cb() return None try: # reset to endpoint curr = reset_cb(curr)", "the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current):", "current: Start the search on the current item? @type current: boolean @return: True", "start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method for performing a", "to another item to test @type move_cb: callable @param test_cb: Function to call", "to call to move to another item to test @type move_cb: callable @param", "return None while 1: if test_cb(curr, text): found_cb(curr) end_cb() return True # seek", "first item to test curr = start_cb() try: if not current: curr =", "to wrap pass else: while 1: if test_cb(curr, text): found_cb(curr) end_cb() return False", "contains the text @type test_cb: callable @param found_cb: Function to call when text", "search @type reset_cb: callable @param text: Text to locate @type text: string @param", "we might need to wrap pass else: while 1: if test_cb(curr, text): found_cb(curr)", "try: curr = move_cb(curr) except ValueError: break except AttributeError: end_cb() return None try:", "move_cb(curr) except ValueError: break except AttributeError: end_cb() return None try: # reset to", "perform a circular search through a body of items. How the search proceeds", "end_cb() return None while 1: if test_cb(curr, text): found_cb(curr) end_cb() return True #", "''' class CircularSearchMixin(object): ''' Mixing providing a generic method using callbacks to perform", "current: curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors here, we", "test if an item contains the text @type test_cb: callable @param found_cb: Function", "move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors here, we might need to", "end_cb() return True # seek in desired direction try: curr = move_cb(curr) except", "U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a generic method using callbacks to", "BSD License which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class", "not wrapped, None if not found @rtype: boolean ''' # set to first", "found in an item @type found_cb: callable @param reset_cb: Function to call when", "circular search through a body of items. How the search proceeds is entirely", "found_cb: Function to call when text is found in an item @type found_cb:", "1: if test_cb(curr, text): found_cb(curr) end_cb() return True # seek in desired direction", "callable @param text: Text to locate @type text: string @param current: Start the", "(c) 2008 <NAME> @license: BSD License All rights reserved. This program and the", "start_cb: callable @param end_cb: Function to call when the search is ending @type", "callable @param found_cb: Function to call when text is found in an item", "pass else: while 1: if test_cb(curr, text): found_cb(curr) end_cb() return False # seek", "Function to call when the search is starting @type start_cb: callable @param end_cb:", "# ignore any errors here, we might need to wrap pass else: while", "if test_cb(curr, text): found_cb(curr) end_cb() return False # seek in desired direction try:", "''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method", "Function to call when text is found in an item @type found_cb: callable", "search is ending @type end_cb: callable @param move_cb: Function to call to move", "by the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text,", "are made available under the terms of The BSD License which accompanies this", "a circular search through a body of items. How the search proceeds is", "How the search proceeds is entirely defined by the callbacks. ''' def CircularSearch(self,", "the text @type test_cb: callable @param found_cb: Function to call when text is", "search related mixins. @author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD", "locate @type text: string @param current: Start the search on the current item?", "accompanying materials are made available under the terms of The BSD License which", "a generic method using callbacks to perform a circular search through a body", "callbacks to perform a circular search through a body of items. How the", "start_cb: Function to call when the search is starting @type start_cb: callable @param", "Mixing providing a generic method using callbacks to perform a circular search through", "test @type move_cb: callable @param test_cb: Function to call to test if an", "''' # set to first item to test curr = start_cb() try: if", "a generic, wrapping search over an entire collection. @param start_cb: Function to call", "the current item? @type current: boolean @return: True if wrapped, False if not", "@param test_cb: Function to call to test if an item contains the text", "''' Mixing providing a generic method using callbacks to perform a circular search", "set to first item to test curr = start_cb() try: if not current:", "entirely defined by the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb,", "= start_cb() try: if not current: curr = move_cb(start_cb()) except (ValueError, AttributeError): #", "(ValueError, AttributeError): # ignore any errors here, we might need to wrap pass", "wrap pass else: while 1: if test_cb(curr, text): found_cb(curr) end_cb() return False #", "= move_cb(curr) except ValueError: break except AttributeError: end_cb() return None try: # reset", "call to test if an item contains the text @type test_cb: callable @param", "is found in an item @type found_cb: callable @param reset_cb: Function to call", "found_cb: callable @param reset_cb: Function to call when wrapping during search @type reset_cb:", "except (ValueError, AttributeError): end_cb() return None while 1: if test_cb(curr, text): found_cb(curr) end_cb()", "curr = move_cb(curr) except ValueError: break except AttributeError: end_cb() return None try: #", "callable @param end_cb: Function to call when the search is ending @type end_cb:", "to test @type move_cb: callable @param test_cb: Function to call to test if", "an item contains the text @type test_cb: callable @param found_cb: Function to call", "@param move_cb: Function to call to move to another item to test @type", "Method for performing a generic, wrapping search over an entire collection. @param start_cb:", "item contains the text @type test_cb: callable @param found_cb: Function to call when", "at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a generic method using callbacks", "of The BSD License which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php}", "the accompanying materials are made available under the terms of The BSD License", "test_cb(curr, text): found_cb(curr) end_cb() return False # seek in desired direction try: curr", "text @type test_cb: callable @param found_cb: Function to call when text is found", "2008 <NAME> @license: BSD License All rights reserved. This program and the accompanying", "''' Method for performing a generic, wrapping search over an entire collection. @param", "end_cb() return None try: # reset to endpoint curr = reset_cb(curr) except (ValueError,", "to move to another item to test @type move_cb: callable @param test_cb: Function", "@license: BSD License All rights reserved. This program and the accompanying materials are", "another item to test @type move_cb: callable @param test_cb: Function to call to", "@author: <NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD License All rights", "the search is starting @type start_cb: callable @param end_cb: Function to call when", "break except AttributeError: end_cb() return None try: # reset to endpoint curr =", "not current: curr = move_cb(start_cb()) except (ValueError, AttributeError): # ignore any errors here,", "desired direction try: curr = move_cb(curr) except ValueError: break except AttributeError: end_cb() return", "# seek in desired direction try: curr = move_cb(curr) except (ValueError, AttributeError): break", "AttributeError): # ignore any errors here, we might need to wrap pass else:", "reset_cb: callable @param text: Text to locate @type text: string @param current: Start", "current): ''' Method for performing a generic, wrapping search over an entire collection.", "return None try: # reset to endpoint curr = reset_cb(curr) except (ValueError, AttributeError):", "@type start_cb: callable @param end_cb: Function to call when the search is ending", "boolean @return: True if wrapped, False if not wrapped, None if not found", "Text to locate @type text: string @param current: Start the search on the", "@param start_cb: Function to call when the search is starting @type start_cb: callable", "collection. @param start_cb: Function to call when the search is starting @type start_cb:", "is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a generic method", "a body of items. How the search proceeds is entirely defined by the", "The BSD License which accompanies this distribution, and is available at U{http://www.opensource.org/licenses/bsd-license.php} '''", "None while 1: if test_cb(curr, text): found_cb(curr) end_cb() return True # seek in", "to call to test if an item contains the text @type test_cb: callable", "wrapped, False if not wrapped, None if not found @rtype: boolean ''' #", "1: if test_cb(curr, text): found_cb(curr) end_cb() return False # seek in desired direction", "Copyright (c) 2008 <NAME> @license: BSD License All rights reserved. This program and", "here, we might need to wrap pass else: while 1: if test_cb(curr, text):", "of items. How the search proceeds is entirely defined by the callbacks. '''", "through a body of items. How the search proceeds is entirely defined by", "<NAME> <<EMAIL>> @copyright: Copyright (c) 2008 <NAME> @license: BSD License All rights reserved.", "# set to first item to test curr = start_cb() try: if not", "curr = reset_cb(curr) except (ValueError, AttributeError): end_cb() return None while 1: if test_cb(curr,", "except ValueError: break except AttributeError: end_cb() return None try: # reset to endpoint", "True # seek in desired direction try: curr = move_cb(curr) except (ValueError, AttributeError):", "the search is ending @type end_cb: callable @param move_cb: Function to call to", "@param text: Text to locate @type text: string @param current: Start the search", "call when wrapping during search @type reset_cb: callable @param text: Text to locate", "boolean ''' # set to first item to test curr = start_cb() try:", "def CircularSearch(self, start_cb, end_cb, move_cb, test_cb, found_cb, reset_cb, text, current): ''' Method for", "when the search is ending @type end_cb: callable @param move_cb: Function to call", "test_cb(curr, text): found_cb(curr) end_cb() return True # seek in desired direction try: curr", "desired direction try: curr = move_cb(curr) except (ValueError, AttributeError): break end_cb() return None", "for performing a generic, wrapping search over an entire collection. @param start_cb: Function", "to call when text is found in an item @type found_cb: callable @param", "to locate @type text: string @param current: Start the search on the current", "search over an entire collection. @param start_cb: Function to call when the search", "if an item contains the text @type test_cb: callable @param found_cb: Function to", "Function to call when wrapping during search @type reset_cb: callable @param text: Text", "test_cb: Function to call to test if an item contains the text @type", "@type current: boolean @return: True if wrapped, False if not wrapped, None if", "not found @rtype: boolean ''' # set to first item to test curr", "need to wrap pass else: while 1: if test_cb(curr, text): found_cb(curr) end_cb() return", "return False # seek in desired direction try: curr = move_cb(curr) except ValueError:", "@type text: string @param current: Start the search on the current item? @type", "proceeds is entirely defined by the callbacks. ''' def CircularSearch(self, start_cb, end_cb, move_cb,", "class CircularSearchMixin(object): ''' Mixing providing a generic method using callbacks to perform a", "callable @param test_cb: Function to call to test if an item contains the", "to call when wrapping during search @type reset_cb: callable @param text: Text to", "over an entire collection. @param start_cb: Function to call when the search is", "BSD License All rights reserved. This program and the accompanying materials are made", "rights reserved. This program and the accompanying materials are made available under the", "and is available at U{http://www.opensource.org/licenses/bsd-license.php} ''' class CircularSearchMixin(object): ''' Mixing providing a generic", "on the current item? @type current: boolean @return: True if wrapped, False if", "direction try: curr = move_cb(curr) except ValueError: break except AttributeError: end_cb() return None" ]
[ "import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager',", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations", "class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client',", "unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'),", "migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField(", "django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations", "('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email', field=models.EmailField(default=b'', max_length=254, blank=True), ),", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class", "<reponame>gregplaysguitar/django-projectmanager # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email',", "-*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies", "import models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations =", "= [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email', field=models.EmailField(default=b'', max_length=254,", "dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email', field=models.EmailField(default=b'',", "from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies =", "__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [", "'0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email', field=models.EmailField(default=b'', max_length=254, blank=True), ), ]", "[ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [ migrations.AddField( model_name='client', name='email', field=models.EmailField(default=b'', max_length=254, blank=True),", "models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ] operations = [", "utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):", "from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0009_auto_20150414_1019'), ]", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models," ]
[ "136, 153 ), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\": ( 221, 160,", "130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": ( 0, 0,", "192, 192, 192 ), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": ( 218,", "193 ), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\": ( 255, 215, 0", ") #lowercase_html_colors = { key.lower(): value for key, value in capitalized_html_colors.items() } def", "), \"Violet\": ( 238, 130, 238 ), \"Grey\": ( 128, 128, 128 ),", "( 250, 240, 230 ), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": (", "105, 105 ), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": ( 250, 235,", "( 178, 34, 34 ), \"Violet\": ( 238, 130, 238 ), \"Grey\": (", "248, 255 ), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": ( 255, 250,", "), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": ( 0, 206, 209 ),", "( 245, 255, 250 ), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": (", "79, 79 ), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": ( 153, 50,", "\"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\":", "\"Lime\": ( 0, 255, 0 ), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\":", "105 ), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": ( 250, 235, 215", "107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": ( 0, 255,", "\"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\":", "\"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\":", "\"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\":", "60 ), \"White\": ( 255, 255, 255 ), \"NavajoWhite\": ( 255, 222, 173", "( 0, 0, 139 ), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": (", "\"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\":", "\"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\":", "\"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": ( 192, 192, 192 ), \"LightGray\":", "0, 128 ), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": ( 128, 128,", "230 ), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": ( 199, 21, 133", "\"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\":", "112, 147 ), \"FireBrick\": ( 178, 34, 34 ), \"Violet\": ( 238, 130,", "), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": ( 139, 0, 139 ),", "179, 113 ), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": ( 64, 224,", "0, 128, 128 ), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": ( 176,", "\"Teal\": ( 0, 128, 128 ), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\":", "), \"Crimson\": ( 220, 20, 60 ), \"White\": ( 255, 255, 255 ),", "154 ), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": ( 0, 255, 255", "\"SpringGreen\": ( 0, 255, 127 ), \"Navy\": ( 0, 0, 128 ), \"Orchid\":", "( 216, 112, 147 ), \"FireBrick\": ( 178, 34, 34 ), \"Violet\": (", "\"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\":", "\"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\":", "250, 128, 114 ), \"IndianRed\": ( 205, 92, 92 ), \"Snow\": ( 255,", "\"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\":", "0 ), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": ( 124, 252, 0", "\"Chocolate\": ( 210, 105, 30 ), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\":", "( 144, 238, 144 ), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\": (", "\"Chartreuse\": ( 127, 255, 0 ), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\":", "), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": ( 0, 0, 0 ),", "196, 222 ), \"DimGrey\": ( 105, 105, 105 ), \"Tan\": ( 210, 180,", "\"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\":", "\"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\":", "128, 144 ), \"Gold\": ( 255, 215, 0 ), \"OldLace\": ( 253, 245,", "\"Blue\": ( 0, 0, 255 ), \"Pink\": ( 255, 192, 203 ), \"Darkorange\":", "( 135, 206, 250 ), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": (", "\"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\":", "), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143 ),", "( 255, 215, 0 ), \"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors", "221 ), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": ( 245, 255, 250", "245, 220 ), \"Teal\": ( 0, 128, 128 ), \"Azure\": ( 240, 255,", "( 255, 250, 250 ), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": (", "128, 0 ), \"Beige\": ( 245, 245, 220 ), \"Teal\": ( 0, 128,", "140 ), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": ( 135, 206, 235", "0 ), \"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors = dict( ((key.lower(),", "128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": ( 255,", "203 ), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": ( 255, 0, 255", "\"IndianRed\": ( 205, 92, 92 ), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\":", "250, 235, 215 ), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": ( 248,", "\"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\":", "( 135, 206, 235 ), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": (", "20, 147 ), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\": ( 255, 0,", "255, 255 ), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": ( 255, 248,", "( 255, 218, 185 ), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": (", "( 0, 206, 209 ), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": (", "47 ), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210", "\"Linen\": ( 250, 240, 230 ), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\":", "139, 69, 19 ), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": ( 255,", "\"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\":", "), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": ( 255, 250, 205 ),", "144 ), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": ( 135, 206, 250", "\"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\":", "245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": ( 30,", "240 ), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": ( 46, 139, 87", "92, 92 ), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\": ( 70, 130,", "47, 79, 79 ), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": ( 222,", "), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": ( 218, 165, 32 ),", "185 ), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170", "\"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\":", "( 205, 92, 92 ), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\": (", "\"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\":", "105 ), \"Maroon\": ( 128, 0, 0 ), \"LightPink\": ( 255, 182, 193", "99, 71 ), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250,", "value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for", "206, 235 ), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": ( 240, 255,", "238 ), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113", "213 ), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": ( 119, 136, 153", "128 ), \"Orchid\": ( 218, 112, 214 ), \"Salmon\": ( 250, 128, 114", "250, 210 ), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": ( 127, 255,", "\"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\":", "112, 128, 144 ), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": ( 135,", "154, 205, 50 ), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": ( 240,", "( 222, 184, 135 ), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": (", "211, 211 ), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": ( 220, 220,", "\"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\":", "( 255, 250, 205 ), \"Silver\": ( 192, 192, 192 ), \"LightGray\": (", "160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": ( 245, 255,", "238, 130, 238 ), \"Grey\": ( 128, 128, 128 ), \"LightGreen\": ( 144,", "\"Violet\": ( 238, 130, 238 ), \"Grey\": ( 128, 128, 128 ), \"LightGreen\":", "), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": ( 107, 142, 35 ),", "112, 128, 144 ), \"Gold\": ( 255, 215, 0 ), \"OldLace\": ( 253,", "\"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\":", "( 119, 136, 153 ), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": (", "\"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": ( 160, 82, 45 ), \"Thistle\":", "128 ), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": ( 128, 128, 0", "211, 211, 211 ), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": ( 75,", "( 0, 255, 255 ), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": (", "\"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\":", "), \"Sienna\": ( 160, 82, 45 ), \"Thistle\": ( 216, 191, 216 ),", "( 123, 104, 238 ), \"Black\": ( 0, 0, 0 ), \"LightBlue\": (", "255, 127 ), \"Navy\": ( 0, 0, 128 ), \"Orchid\": ( 218, 112,", "), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\": ( 0, 0, 128 ),", "85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": ( 0,", "), \"IndianRed\": ( 205, 92, 92 ), \"Snow\": ( 255, 250, 250 ),", "), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": ( 0, 0, 205 ),", "178, 34, 34 ), \"Violet\": ( 238, 130, 238 ), \"Grey\": ( 128,", "((key.lower(), value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value", "139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": ( 173, 255,", "80 ), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": ( 128, 128, 128", "240, 248, 255 ), \"Crimson\": ( 220, 20, 60 ), \"White\": ( 255,", "), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154 ),", "160, 122 ), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": ( 178, 34,", "), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": ( 255, 105, 180 ),", "), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": ( 106, 90, 205 ),", "( 165, 42, 42 ), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": (", "), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": ( 75, 0, 130 ),", "47 ), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": ( 0, 255, 127", "\"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\":", "224, 255, 255 ), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": ( 138,", "139 ), \"Green\": ( 0, 128, 0 ), \"Beige\": ( 245, 245, 220", "( 34, 139, 34 ), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": (", "\"PaleGreen\": ( 152, 251, 152 ), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\":", "61, 139 ), \"Green\": ( 0, 128, 0 ), \"Beige\": ( 245, 245,", "240 ), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": ( 255, 240, 245", "), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47 ),", "), \"FireBrick\": ( 178, 34, 34 ), \"Violet\": ( 238, 130, 238 ),", "( 105, 105, 105 ), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": (", "( 107, 142, 35 ), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\": (", "( 30, 144, 255 ), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": (", "( 0, 250, 154 ), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": (", "), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": ( 139, 0, 0 ),", "158, 160 ), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": ( 176, 224,", "( 0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": (", "( 127, 255, 0 ), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": (", "105, 105 ), \"Maroon\": ( 128, 0, 0 ), \"LightPink\": ( 255, 182,", "169, 169, 169 ), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": ( 47,", "\"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\":", "), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11 ),", "50 ), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": ( 189, 183, 107", "\"Wheat\": ( 245, 222, 179 ), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\":", "255 ), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": ( 240, 248, 255", "0, 0 ), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": ( 106, 90,", "( 255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": (", "), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\": ( 255, 69, 0 ),", "( 253, 245, 230 ) } lowercase_html_colors = dict( ((key.lower(), value) for key,", "\"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\":", "0, 255 ), \"Pink\": ( 255, 192, 203 ), \"Darkorange\": ( 255, 140,", "205 ), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": ( 127, 255, 212", "237 ), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": ( 0, 0, 139", "( 255, 165, 0 ), \"Red\": ( 255, 0, 0 ), \"Wheat\": (", "230 ), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170", "( 248, 248, 255 ), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": (", "\"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\":", "30 ), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": ( 255, 239, 213", "( 255, 222, 173 ), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": (", "\"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\":", "233, 150, 122 ), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": ( 255,", "176, 196, 222 ), \"DimGrey\": ( 105, 105, 105 ), \"Tan\": ( 210,", "152, 251, 152 ), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": ( 0,", "42, 42 ), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": ( 0, 100,", "\"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\":", "( 189, 183, 107 ), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\": (", "), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\": ( 255, 255, 240 ),", "255, 140, 0 ), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": ( 124,", "245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": ( 30, 144,", "), \"Lime\": ( 0, 255, 0 ), \"SlateGray\": ( 112, 128, 144 ),", "\"Orchid\": ( 218, 112, 214 ), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\":", "0, 206, 209 ), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": ( 184,", "( 240, 248, 255 ), \"Crimson\": ( 220, 20, 60 ), \"White\": (", "220 ), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": ( 244, 164, 96", "205, 133, 63 ), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": ( 255,", "( 255, 0, 0 ), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\": (", "216 ), \"Lime\": ( 0, 255, 0 ), \"SlateGray\": ( 112, 128, 144", "), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\": ( 255, 215, 0 ),", "92 ), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\": ( 70, 130, 180", "), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": ( 189, 183, 107 ),", "238, 144 ), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\": ( 255, 69,", "255, 0 ), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": ( 255, 228,", "191, 216 ), \"Lime\": ( 0, 255, 0 ), \"SlateGray\": ( 112, 128,", "\"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\":", "\"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\":", "139 ), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": ( 173, 255, 47", "136, 153 ), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": ( 147, 112,", "( 255, 20, 147 ), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\": (", "128, 128 ), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": ( 176, 196,", "169 ), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": ( 139, 0, 139", "255, 20, 147 ), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\": ( 255,", "\"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\":", "255, 0 ), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": ( 72, 209,", "100, 149, 237 ), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": ( 0,", "205 ), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": ( 188, 143, 143", "\"Salmon\": ( 250, 128, 114 ), \"IndianRed\": ( 205, 92, 92 ), \"Snow\":", "\"Gold\": ( 255, 215, 0 ), \"OldLace\": ( 253, 245, 230 ) }", "\"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\":", "( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": (", "0 ), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\": ( 224, 255, 255", "( 255, 245, 238 ), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": (", "( 233, 150, 122 ), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": (", "180, 140 ), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": ( 135, 206,", "105, 225 ), \"Sienna\": ( 160, 82, 45 ), \"Thistle\": ( 216, 191,", "( 160, 82, 45 ), \"Thistle\": ( 216, 191, 216 ), \"Lime\": (", "), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": ( 255, 228, 196 ),", "), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": ( 210, 105, 30 ),", "75, 0, 130 ), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": ( 255,", "= { \"Blue\": ( 0, 0, 255 ), \"Pink\": ( 255, 192, 203", "153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": ( 107,", "165, 42, 42 ), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": ( 0,", "133, 63 ), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": ( 255, 165,", "149, 237 ), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": ( 0, 0,", "\"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\":", "228, 225 ), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": ( 255, 20,", "112, 214 ), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\": ( 205, 92,", "\"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\":", "\"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\":", "205 ), \"Silver\": ( 192, 192, 192 ), \"LightGray\": ( 211, 211, 211", "\"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\":", "( 139, 0, 139 ), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": (", "245, 222, 179 ), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": ( 32,", "( 176, 224, 230 ), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": (", "), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": ( 222, 184, 135 ),", "96 ), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": ( 255, 245, 238", "( 176, 196, 222 ), \"DimGrey\": ( 105, 105, 105 ), \"Tan\": (", "19 ), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": ( 255, 99, 71", "( 65, 105, 225 ), \"Sienna\": ( 160, 82, 45 ), \"Thistle\": (", "135, 206, 235 ), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": ( 240,", "\"Maroon\": ( 128, 0, 0 ), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\":", "( 128, 0, 128 ), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": (", "230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": ( 85,", "( 143, 188, 143 ), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\": (", "255, 255 ), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": ( 138, 43,", "87 ), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205", "( 255, 99, 71 ), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": (", "( 255, 228, 181 ), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": (", "), \"Black\": ( 0, 0, 0 ), \"LightBlue\": ( 173, 216, 230 ),", "255, 250, 240 ), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": ( 46,", "), \"LightGreen\": ( 144, 238, 144 ), \"Linen\": ( 250, 240, 230 ),", "210, 105, 30 ), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": ( 255,", "\"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\":", "( 112, 128, 144 ), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": (", "\"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\":", "240, 255, 255 ), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": ( 105,", "0, 211 ), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": ( 139, 69,", "30, 144, 255 ), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": ( 34,", "\"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\":", "( 72, 209, 204 ), \"Orange\": ( 255, 165, 0 ), \"Red\": (", "170 ), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": ( 119, 136, 153", "\"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\":", "255 ), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": ( 34, 139, 34", "169 ), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79", "143, 188, 143 ), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\": ( 0,", "139, 34 ), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": ( 192, 192,", "255 ), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": ( 25, 25, 112", "( 255, 239, 213 ), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": (", "( 0, 255, 127 ), \"Navy\": ( 0, 0, 128 ), \"Orchid\": (", "255, 222, 173 ), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": ( 255,", "\"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\":", "), \"Navy\": ( 0, 0, 128 ), \"Orchid\": ( 218, 112, 214 ),", "), \"Silver\": ( 192, 192, 192 ), \"LightGray\": ( 211, 211, 211 ),", "), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": ( 220, 220, 220 ),", "), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": ( 47, 79, 79 ),", "205, 92, 92 ), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\": ( 70,", "255, 215, 0 ), \"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors =", "255, 250 ), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": ( 255, 105,", "( 46, 139, 87 ), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": (", "225 ), \"Sienna\": ( 160, 82, 45 ), \"Thistle\": ( 216, 191, 216", "0, 130 ), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": ( 255, 255,", "( 0, 0, 128 ), \"Orchid\": ( 218, 112, 214 ), \"Salmon\": (", "\"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\":", "60, 179, 113 ), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": ( 64,", "255, 250, 205 ), \"Silver\": ( 192, 192, 192 ), \"LightGray\": ( 211,", "\"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\":", "250, 240, 230 ), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": ( 238,", "), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": ( 124, 252, 0 ),", "186, 85, 211 ), \"Chocolate\": ( 210, 105, 30 ), \"Purple\": ( 128,", "255, 255, 240 ), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": ( 148,", "11 ), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": ( 210, 105, 30", "( 250, 128, 114 ), \"IndianRed\": ( 205, 92, 92 ), \"Snow\": (", "\"DimGray\": ( 105, 105, 105 ), \"Maroon\": ( 128, 0, 0 ), \"LightPink\":", "( 85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": (", "255, 224 ), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": ( 65, 105,", "\"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\":", "225 ), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": ( 255, 20, 147", "( 60, 179, 113 ), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": (", "( 173, 216, 230 ), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": (", "), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": ( 127, 255, 212 ),", "\"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\":", "), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": ( 72, 209, 204 ),", "), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": ( 30, 144, 255 ),", "20, 60 ), \"White\": ( 255, 255, 255 ), \"NavajoWhite\": ( 255, 222,", "\"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\":", "\"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\":", "245 ), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": ( 230, 230, 250", "( 210, 105, 30 ), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": (", "\"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\":", "), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": ( 128, 128, 0 ),", "), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": ( 230, 230, 250 ),", "212 ), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": ( 47, 79, 79", "255, 255, 224 ), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": ( 65,", "181 ), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139", "79 ), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": ( 222, 184, 135", "128 ), \"LightGreen\": ( 144, 238, 144 ), \"Linen\": ( 250, 240, 230", "255, 47 ), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250,", "( 255, 182, 193 ), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\": (", "( 220, 20, 60 ), \"White\": ( 255, 255, 255 ), \"NavajoWhite\": (", "), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": ( 0, 255, 255 ),", "235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188,", "\"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\":", "244, 164, 96 ), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": ( 255,", "), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": ( 119, 136, 153 ),", "), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79 ),", "( 255, 250, 240 ), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": (", "\"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\":", "\"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\":", "\"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\":", "248, 220 ), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": ( 152, 251,", "( 128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": (", "( 106, 90, 205 ), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": (", "\"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\":", "211 ), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": ( 75, 0, 130", "\"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\":", "\"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\":", "( 218, 165, 32 ), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": (", "( 0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": (", "255 ), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": ( 255, 250, 240", "\"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": ( 105, 105, 105 ), \"Maroon\":", "), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": ( 64, 224, 208 ),", "143 ), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": ( 216, 112, 147", "0 ), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": ( 255, 228, 225", "( 199, 21, 133 ), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": (", "222, 173 ), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": ( 255, 228,", "( 147, 112, 216 ), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": (", "), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": ( 135, 206, 235 ),", "), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": ( 192, 192, 192 ),", "\"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\":", "173 ), \"Cornsilk\": ( 255, 248, 220 ), \"Bisque\": ( 255, 228, 196", "( 154, 205, 50 ), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": (", "63 ), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": ( 255, 165, 0", "\"Silver\": ( 192, 192, 192 ), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\":", "\"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\":", "), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170 ),", "113 ), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\": ( 64, 224, 208", "), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255 ),", "0 ), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": ( 220, 20, 60", "255, 105, 180 ), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": ( 50,", "255, 240 ), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": ( 255, 240,", "0, 250, 154 ), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": ( 0,", "( 105, 105, 105 ), \"Maroon\": ( 128, 0, 0 ), \"LightPink\": (", "255 ), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": ( 105, 105, 105", "( 255, 0, 255 ), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": (", "\"LightGreen\": ( 144, 238, 144 ), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\":", "250 ), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": ( 255, 105, 180", "192 ), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": ( 218, 165, 32", "\"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": ( 105, 105, 105 ), \"Tan\":", "79, 79 ), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": ( 222, 184,", "( 47, 79, 79 ), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": (", "\"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\":", "252, 0 ), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": ( 220, 20,", "), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": ( 199, 21, 133 ),", "226 ), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": ( 0, 255, 255", "69, 19 ), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": ( 255, 99,", "), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": ( 255, 0, 255 ),", "( 0, 0, 255 ), \"Pink\": ( 255, 192, 203 ), \"Darkorange\": (", "\"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\":", "\"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\":", "( 0, 128, 0 ), \"Beige\": ( 245, 245, 220 ), \"Teal\": (", "), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": ( 176, 224, 230 ),", "50 ), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": ( 240, 128, 128", "255, 0 ), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": ( 139, 0,", "128 ), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": ( 176, 196, 222", ") } lowercase_html_colors = dict( ((key.lower(), value) for key, value in capitalized_html_colors.items()) )", "47, 79, 79 ), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": ( 153,", "\"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\":", "211 ), \"Chocolate\": ( 210, 105, 30 ), \"Purple\": ( 128, 0, 128", "206, 250 ), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": ( 154, 205,", "144, 255 ), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": ( 34, 139,", "( 255, 0, 255 ), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": (", "), \"Green\": ( 0, 128, 0 ), \"Beige\": ( 245, 245, 220 ),", "( 255, 255, 255 ), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": (", "0 ), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": ( 112, 128, 144", "), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\": ( 255, 255, 0 ),", "), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": ( 0, 139, 139 ),", "( 148, 0, 211 ), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": (", "206, 209 ), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134,", "\"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": ( 178, 34, 34 ), \"Violet\":", "( 50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": (", "( 244, 164, 96 ), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": (", "104, 238 ), \"Black\": ( 0, 0, 0 ), \"LightBlue\": ( 173, 216,", "211 ), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": ( 139, 69, 19", "( 0, 0, 0 ), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\": (", "238 ), \"Black\": ( 0, 0, 0 ), \"LightBlue\": ( 173, 216, 230", "( 255, 192, 203 ), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": (", "240, 230, 140 ), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": ( 0,", "188, 143 ), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\": ( 0, 0,", "130 ), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": ( 255, 255, 224", "0, 0 ), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": ( 112, 128,", "( 32, 178, 170 ), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": (", "127, 80 ), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": ( 128, 128,", "), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": ( 112, 128, 144 ),", "), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": ( 255, 20, 147 ),", "\"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": ( 255, 228, 181 ), \"Turquoise\":", "), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": ( 255, 228, 181 ),", "0 ), \"Red\": ( 255, 0, 0 ), \"Wheat\": ( 245, 222, 179", "255, 255, 255 ), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": ( 255,", "), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\": ( 205, 92, 92 ),", "0, 0 ), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\": ( 255, 255,", "211, 211, 211 ), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": ( 220,", "( 192, 192, 192 ), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": (", "( 139, 0, 0 ), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": (", "( 188, 143, 143 ), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": (", "255, 127, 80 ), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": ( 128,", "42 ), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": ( 0, 100, 0", "34, 139, 34 ), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": ( 192,", "255, 99, 71 ), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": ( 0,", "255 ), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": ( 255, 248, 220", "255, 255 ), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": ( 105, 105,", "140 ), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": ( 0, 0, 205", "\"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\":", "180 ), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": ( 0, 0, 0", "255, 0, 255 ), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": ( 240,", "255 ), \"Crimson\": ( 220, 20, 60 ), \"White\": ( 255, 255, 255", "105, 30 ), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": ( 255, 239,", "\"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\":", "( 220, 220, 220 ), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": (", "46, 139, 87 ), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": ( 255,", "147 ), \"FireBrick\": ( 178, 34, 34 ), \"Violet\": ( 238, 130, 238", "), \"Gold\": ( 255, 215, 0 ), \"OldLace\": ( 253, 245, 230 )", "240, 255, 240 ), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": ( 255,", "173, 216, 230 ), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": ( 199,", "), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": ( 152, 251, 152 ),", "128 ), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": ( 255, 228, 181", "( 211, 211, 211 ), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": (", "128, 0, 0 ), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": ( 112,", "), \"Snow\": ( 255, 250, 250 ), \"SteelBlue\": ( 70, 130, 180 ),", "0, 0, 205 ), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": ( 188,", "= { key.lower(): value for key, value in capitalized_html_colors.items() } def get_color_tuple_by_name(colorname): return", "255, 255 ), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": ( 25, 25,", "147, 112, 216 ), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": ( 255,", "), \"Chocolate\": ( 210, 105, 30 ), \"Purple\": ( 128, 0, 128 ),", "( 139, 69, 19 ), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": (", "value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for key, value in", "142, 35 ), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\": ( 205, 133,", "178, 170 ), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": ( 119, 136,", "160 ), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": ( 176, 224, 230", "245, 238 ), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": ( 169, 169,", "255, 245, 238 ), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": ( 169,", "( 224, 255, 255 ), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": (", "\"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\":", "255, 165, 0 ), \"Red\": ( 255, 0, 0 ), \"Wheat\": ( 245,", "), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": ( 0, 100, 0 ),", "114 ), \"IndianRed\": ( 205, 92, 92 ), \"Snow\": ( 255, 250, 250", "( 0, 128, 128 ), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": (", "( 211, 211, 211 ), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": (", "205, 170 ), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": ( 100, 149,", "79 ), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": ( 153, 50, 204", "), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": ( 220, 20, 60 ),", "180 ), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": ( 50, 205, 50", "\"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": ( 255, 165, 0 ), \"Red\":", "122 ), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": ( 178, 34, 34", "( 47, 79, 79 ), \"Khaki\": ( 240, 230, 140 ), \"BurlyWood\": (", "( 210, 180, 140 ), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": (", "), \"Teal\": ( 0, 128, 128 ), \"Azure\": ( 240, 255, 255 ),", "255, 228, 225 ), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": ( 255,", "\"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\":", "), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\": ( 224, 255, 255 ),", "), \"Orchid\": ( 218, 112, 214 ), \"Salmon\": ( 250, 128, 114 ),", "124, 252, 0 ), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": ( 220,", "21, 133 ), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": ( 169, 169,", "255, 228, 181 ), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": ( 72,", "( 255, 240, 245 ), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": (", "\"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\":", "\"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\":", "215 ), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": ( 248, 248, 255", "0, 0, 0 ), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\": ( 255,", "220, 20, 60 ), \"White\": ( 255, 255, 255 ), \"NavajoWhite\": ( 255,", "240 ), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": ( 148, 0, 211", "), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": ( 255, 218, 185 ),", "), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\": ( 255, 248, 220 ),", "\"Beige\": ( 245, 245, 220 ), \"Teal\": ( 0, 128, 128 ), \"Azure\":", "( 138, 43, 226 ), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": (", "139 ), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": ( 245, 245, 245", "\"LightBlue\": ( 173, 216, 230 ), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\":", "25, 112 ), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": ( 175, 238,", "\"SeaShell\": ( 255, 245, 238 ), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\":", "\"Grey\": ( 128, 128, 128 ), \"LightGreen\": ( 144, 238, 144 ), \"Linen\":", "128, 114 ), \"IndianRed\": ( 205, 92, 92 ), \"Snow\": ( 255, 250,", "), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": ( 160, 82, 45 ),", "255, 240, 245 ), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": ( 230,", "175, 238, 238 ), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": ( 60,", "), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": ( 173, 255, 47 ),", "#lowercase_html_colors = { key.lower(): value for key, value in capitalized_html_colors.items() } def get_color_tuple_by_name(colorname):", "( 245, 245, 220 ), \"Teal\": ( 0, 128, 128 ), \"Azure\": (", "255, 250, 250 ), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": ( 123,", "0, 0, 255 ), \"Pink\": ( 255, 192, 203 ), \"Darkorange\": ( 255,", "( 112, 128, 144 ), \"Gold\": ( 255, 215, 0 ), \"OldLace\": (", "( 184, 134, 11 ), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": (", "( 128, 128, 128 ), \"LightGreen\": ( 144, 238, 144 ), \"Linen\": (", "\"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\":", "), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113 ),", "( 255, 228, 225 ), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\": (", "0, 0 ), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\": ( 224, 255,", "122 ), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": ( 255, 160, 122", "( 75, 0, 130 ), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": (", "( 152, 251, 152 ), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": (", "248, 248, 255 ), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": ( 255,", "\"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\":", "0 ), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": ( 106, 90, 205", "184, 135 ), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": ( 233, 150,", "), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": ( 127, 255, 0 ),", "( 216, 191, 216 ), \"Lime\": ( 0, 255, 0 ), \"SlateGray\": (", "), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": ( 255, 228, 225 ),", "220, 220 ), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": ( 244, 164,", "128, 0 ), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": ( 255, 218,", "128, 128 ), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": ( 240, 230,", "), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": ( 233, 150, 122 ),", "255, 240 ), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": ( 148, 0,", "170 ), \"DimGray\": ( 105, 105, 105 ), \"Maroon\": ( 128, 0, 0", "139 ), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255", "( 127, 255, 212 ), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": (", "), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": ( 248, 248, 255 ),", "\"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\":", "), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ),", "\"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\":", "( 0, 0, 205 ), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": (", "232, 170 ), \"DimGray\": ( 105, 105, 105 ), \"Maroon\": ( 128, 0,", "255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": ( 143,", "255, 239, 213 ), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": ( 119,", "), \"White\": ( 255, 255, 255 ), \"NavajoWhite\": ( 255, 222, 173 ),", "\"LightGrey\": ( 211, 211, 211 ), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\":", "), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": ( 100, 149, 237 ),", "64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": ( 0,", "), \"Azure\": ( 240, 255, 255 ), \"LightSteelBlue\": ( 176, 196, 222 ),", "\"PeachPuff\": ( 255, 218, 185 ), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\":", "), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": ( 154, 205, 50 ),", "0, 0, 128 ), \"Orchid\": ( 218, 112, 214 ), \"Salmon\": ( 250,", "230, 140 ), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": ( 0, 0,", "( 102, 205, 170 ), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": (", "\"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\":", "0, 139 ), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191,", "( 173, 255, 47 ), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": (", "211, 211 ), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\": ( 75, 0,", "210, 180, 140 ), \"AntiqueWhite\": ( 250, 235, 215 ), \"SkyBlue\": ( 135,", "\"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors = dict( ((key.lower(), value) for", "128, 144 ), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": ( 135, 206,", "= dict( ((key.lower(), value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = {", "100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": ( 186, 85,", "\"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\":", "95, 158, 160 ), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": ( 176,", "( 100, 149, 237 ), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": (", "153 ), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": ( 147, 112, 216", "), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238 ),", "\"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\":", "34 ), \"LemonChiffon\": ( 255, 250, 205 ), \"Silver\": ( 192, 192, 192", "\"SlateGrey\": ( 112, 128, 144 ), \"Gold\": ( 255, 215, 0 ), \"OldLace\":", "0, 128, 0 ), \"Beige\": ( 245, 245, 220 ), \"Teal\": ( 0,", "), \"Grey\": ( 128, 128, 128 ), \"LightGreen\": ( 144, 238, 144 ),", "102, 205, 170 ), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": ( 100,", "), \"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": ( 153, 50, 204 ),", "), \"Red\": ( 255, 0, 0 ), \"Wheat\": ( 245, 222, 179 ),", "127, 255, 212 ), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": ( 47,", "( 240, 255, 240 ), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": (", "255 ), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": ( 211, 211, 211", "235 ), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": ( 240, 255, 240", "( 95, 158, 160 ), \"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": (", "0, 139 ), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": ( 245, 245,", "139, 0, 139 ), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": ( 245,", "173, 255, 47 ), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\": ( 250,", "224 ), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": ( 65, 105, 225", "), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": ( 250, 235, 215 ),", "255, 218, 185 ), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": ( 102,", "214 ), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\": ( 205, 92, 92", "199, 21, 133 ), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": ( 169,", "106, 90, 205 ), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": ( 127,", "220 ), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": ( 152, 251, 152", "( 255, 127, 80 ), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": (", "250, 205 ), \"Silver\": ( 192, 192, 192 ), \"LightGray\": ( 211, 211,", "133 ), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": ( 169, 169, 169", "( 205, 133, 63 ), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": (", "179 ), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": ( 32, 178, 170", "\"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\":", "250 ), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238", "230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107,", "\"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\":", "\"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\":", "), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": ( 169, 169, 169 ),", "\"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\":", "( 250, 250, 210 ), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": (", "255, 0, 0 ), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\": ( 224,", "255, 255, 0 ), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": ( 255,", "0 ), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": ( 255, 218, 185", "0 ), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": ( 72, 209, 204", "( 0, 255, 0 ), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": (", "144, 238, 144 ), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\": ( 255,", "144 ), \"Linen\": ( 250, 240, 230 ), \"OrangeRed\": ( 255, 69, 0", "), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205 ),", "230 ) } lowercase_html_colors = dict( ((key.lower(), value) for key, value in capitalized_html_colors.items())", "} lowercase_html_colors = dict( ((key.lower(), value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors", "( 25, 25, 112 ), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": (", "lowercase_html_colors = dict( ((key.lower(), value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors =", "), \"DarkMagenta\": ( 139, 0, 139 ), \"Tomato\": ( 255, 99, 71 ),", "196 ), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\": ( 165, 42, 42", "189, 183, 107 ), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\": ( 255,", "\"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\":", "), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": ( 50, 205, 50 ),", "43, 226 ), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": ( 0, 255,", "), \"DimGray\": ( 105, 105, 105 ), \"Maroon\": ( 128, 0, 0 ),", "220, 220, 220 ), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": ( 244,", "192, 203 ), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": ( 255, 0,", "143 ), \"SpringGreen\": ( 0, 255, 127 ), \"Navy\": ( 0, 0, 128", "), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": ( 0, 255, 255 ),", "50, 205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": ( 189,", "204 ), \"Orange\": ( 255, 165, 0 ), \"Red\": ( 255, 0, 0", "), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": ( 255, 160, 122 ),", "\"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\":", "112 ), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": ( 175, 238, 238", "), \"GhostWhite\": ( 248, 248, 255 ), \"HoneyDew\": ( 240, 255, 240 ),", "255 ), \"Pink\": ( 255, 192, 203 ), \"Darkorange\": ( 255, 140, 0", "0, 255 ), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": ( 240, 248,", "0, 255, 0 ), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": ( 139,", "( 0, 191, 255 ), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": (", "), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": ( 255, 127, 80 ),", "), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\": ( 135, 206, 250 ),", "\"Orange\": ( 255, 165, 0 ), \"Red\": ( 255, 0, 0 ), \"Wheat\":", "capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for key, value in capitalized_html_colors.items() }", "208 ), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": ( 0, 128, 0", "\"Snow\": ( 255, 250, 250 ), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\":", "\"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": ( 244, 164, 96 ), \"DeepPink\":", "210 ), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": ( 127, 255, 0", "\"Green\": ( 0, 128, 0 ), \"Beige\": ( 245, 245, 220 ), \"Teal\":", "250, 250, 210 ), \"OliveDrab\": ( 107, 142, 35 ), \"Chartreuse\": ( 127,", "105, 105, 105 ), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\": ( 250,", "139, 87 ), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235,", "211 ), \"Yellow\": ( 255, 255, 0 ), \"Gainsboro\": ( 220, 220, 220", "235, 215 ), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": ( 248, 248,", "), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": ( 138, 43, 226 ),", "), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\": ( 165, 42, 42 ),", "( 238, 130, 238 ), \"Grey\": ( 128, 128, 128 ), \"LightGreen\": (", "127, 255, 0 ), \"Peru\": ( 205, 133, 63 ), \"MediumTurquoise\": ( 72,", "0 ), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": ( 186, 85, 211", "), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": ( 178, 34, 34 ),", "), \"MediumTurquoise\": ( 72, 209, 204 ), \"Orange\": ( 255, 165, 0 ),", "143, 143 ), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": ( 216, 112,", "250, 154 ), \"DodgerBlue\": ( 30, 144, 255 ), \"Aqua\": ( 0, 255,", "\"DimGrey\": ( 105, 105, 105 ), \"Tan\": ( 210, 180, 140 ), \"AntiqueWhite\":", "key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for key, value", "216, 112, 147 ), \"FireBrick\": ( 178, 34, 34 ), \"Violet\": ( 238,", "134, 11 ), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": ( 210, 105,", "( 250, 235, 215 ), \"SkyBlue\": ( 135, 206, 235 ), \"GhostWhite\": (", "0, 128 ), \"Orchid\": ( 218, 112, 214 ), \"Salmon\": ( 250, 128,", "( 238, 232, 170 ), \"DimGray\": ( 105, 105, 105 ), \"Maroon\": (", "0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79, 79 ), \"GreenYellow\": ( 173,", "123, 104, 238 ), \"Black\": ( 0, 0, 0 ), \"LightBlue\": ( 173,", "250 ), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": ( 154, 205, 50", "), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\": ( 205, 133, 63 ),", "), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": ( 0, 128, 0 ),", "184, 134, 11 ), \"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": ( 210,", "( 0, 255, 255 ), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": (", "135 ), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": ( 233, 150, 122", "255, 160, 122 ), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": ( 178,", "176, 224, 230 ), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": ( 160,", "230 ), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": ( 160, 82, 45", "165, 32 ), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": ( 95, 158,", "222, 179 ), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": ( 32, 178,", "222, 184, 135 ), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\": ( 233,", "( 240, 128, 128 ), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": (", "\"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\":", "( 255, 105, 180 ), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": (", "), \"Aqua\": ( 0, 255, 255 ), \"ForestGreen\": ( 34, 139, 34 ),", "), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": ( 95, 158, 160 ),", "), \"HotPink\": ( 255, 105, 180 ), \"DarkBlue\": ( 0, 0, 139 ),", "\"Black\": ( 0, 0, 0 ), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\":", "( 255, 255, 0 ), \"Gainsboro\": ( 220, 220, 220 ), \"MistyRose\": (", "228, 196 ), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\": ( 165, 42,", "255, 248, 220 ), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": ( 152,", "( 218, 112, 214 ), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\": (", "127 ), \"Navy\": ( 0, 0, 128 ), \"Orchid\": ( 218, 112, 214", "\"Red\": ( 255, 0, 0 ), \"Wheat\": ( 245, 222, 179 ), \"LightCyan\":", "\"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": ( 218, 165, 32 ), \"Indigo\":", "191, 255 ), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": ( 211, 211,", "153 ), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\": ( 221, 160, 221", "248, 255 ), \"Crimson\": ( 220, 20, 60 ), \"White\": ( 255, 255,", "0 ), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": ( 105, 105, 105", "( 255, 255, 224 ), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": (", "45 ), \"Thistle\": ( 216, 191, 216 ), \"Lime\": ( 0, 255, 0", "169, 169 ), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": ( 47, 79,", "128 ), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": ( 240, 230, 140", "128, 128 ), \"MediumSeaGreen\": ( 60, 179, 113 ), \"Moccasin\": ( 255, 228,", "), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\": ( 128, 128, 128 ),", "\"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\":", "164, 96 ), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": ( 255, 245,", "240, 230 ), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232,", "), \"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors = dict( ((key.lower(), value)", "for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for key,", "), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": ( 119, 136, 153 ),", "\"DarkTurquoise\": ( 0, 206, 209 ), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\":", "128, 128, 0 ), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": ( 255,", "238, 232, 170 ), \"DimGray\": ( 105, 105, 105 ), \"Maroon\": ( 128,", "139, 0, 0 ), \"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": ( 106,", "255, 192, 203 ), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\": ( 255,", "245 ), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": ( 30, 144, 255", "\"Thistle\": ( 216, 191, 216 ), \"Lime\": ( 0, 255, 0 ), \"SlateGray\":", "0 ), \"Beige\": ( 245, 245, 220 ), \"Teal\": ( 0, 128, 128", "( 240, 255, 255 ), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": (", "205, 50 ), \"DeepSkyBlue\": ( 0, 191, 255 ), \"DarkKhaki\": ( 189, 183,", "239, 213 ), \"Olive\": ( 128, 128, 0 ), \"LightSlateGray\": ( 119, 136,", "152 ), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": ( 0, 206, 209", "169, 169, 169 ), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": ( 139,", "70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": ( 0,", "216 ), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": ( 255, 127, 80", "), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": ( 148, 0, 211 ),", "32 ), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": ( 95, 158, 160", "\"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": ( 175, 238, 238 ), \"Gray\":", "\"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": ( 139, 0, 0 ), \"LightSkyBlue\":", "160, 82, 45 ), \"Thistle\": ( 216, 191, 216 ), \"Lime\": ( 0,", "34 ), \"Violet\": ( 238, 130, 238 ), \"Grey\": ( 128, 128, 128", "255, 0, 255 ), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": ( 0,", "105, 105, 105 ), \"Maroon\": ( 128, 0, 0 ), \"LightPink\": ( 255,", "222 ), \"DimGrey\": ( 105, 105, 105 ), \"Tan\": ( 210, 180, 140", "), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": ( 139, 69, 19 ),", "( 245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154 ), \"DodgerBlue\": (", "148, 0, 211 ), \"DarkGray\": ( 169, 169, 169 ), \"SaddleBrown\": ( 139,", "250, 240 ), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": ( 46, 139,", "0, 0, 139 ), \"LimeGreen\": ( 50, 205, 50 ), \"DeepSkyBlue\": ( 0,", "), \"Tomato\": ( 255, 99, 71 ), \"WhiteSmoke\": ( 245, 245, 245 ),", "), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": ( 32, 178, 170 ),", "\"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": ( 0, 0, 0 ), \"LightBlue\":", "105, 180 ), \"DarkBlue\": ( 0, 0, 139 ), \"LimeGreen\": ( 50, 205,", "205, 50 ), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": ( 240, 128,", "), \"LavenderBlush\": ( 255, 240, 245 ), \"SeaGreen\": ( 46, 139, 87 ),", "253, 245, 230 ) } lowercase_html_colors = dict( ((key.lower(), value) for key, value", "), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": ( 188, 143, 143 ),", "255 ), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": ( 255, 250, 205", "\"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": ( 230, 230, 250 ), \"BlanchedAlmond\":", "), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": ( 211, 211, 211 ),", "( 64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": (", "\"Sienna\": ( 160, 82, 45 ), \"Thistle\": ( 216, 191, 216 ), \"Lime\":", "), \"Pink\": ( 255, 192, 203 ), \"Darkorange\": ( 255, 140, 0 ),", "238 ), \"Magenta\": ( 255, 0, 255 ), \"DarkGrey\": ( 169, 169, 169", "209 ), \"DarkGreen\": ( 0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11", "\"LightSkyBlue\": ( 135, 206, 250 ), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\":", "( 255, 255, 240 ), \"MediumVioletRed\": ( 199, 21, 133 ), \"DarkViolet\": (", "72, 209, 204 ), \"Orange\": ( 255, 165, 0 ), \"Red\": ( 255,", "), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\": ( 65, 105, 225 ),", "107, 142, 35 ), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\": ( 205,", "224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": ( 0, 128,", "dict( ((key.lower(), value) for key, value in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower():", "), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61, 139 ),", "), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": ( 240, 230, 140 ),", "( 128, 128, 0 ), \"LightSlateGray\": ( 119, 136, 153 ), \"PeachPuff\": (", "32, 178, 170 ), \"BlueViolet\": ( 138, 43, 226 ), \"LightSlateGrey\": ( 119,", "( 255, 228, 196 ), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\": (", "\"MediumOrchid\": ( 186, 85, 211 ), \"Chocolate\": ( 210, 105, 30 ), \"Purple\":", "( 119, 136, 153 ), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\": (", "170 ), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\": ( 100, 149, 237", "218, 185 ), \"Plum\": ( 221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205,", "183, 107 ), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\": ( 255, 255,", "{ \"Blue\": ( 0, 0, 255 ), \"Pink\": ( 255, 192, 203 ),", "72, 61, 139 ), \"Green\": ( 0, 128, 0 ), \"Beige\": ( 245,", "112, 216 ), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\": ( 255, 127,", "\"Pink\": ( 255, 192, 203 ), \"Darkorange\": ( 255, 140, 0 ), \"Fuchsia\":", "), \"DarkSeaGreen\": ( 143, 188, 143 ), \"SpringGreen\": ( 0, 255, 127 ),", "\"Crimson\": ( 220, 20, 60 ), \"White\": ( 255, 255, 255 ), \"NavajoWhite\":", "), \"Thistle\": ( 216, 191, 216 ), \"Lime\": ( 0, 255, 0 ),", "220 ), \"Teal\": ( 0, 128, 128 ), \"Azure\": ( 240, 255, 255", "capitalized_html_colors = { \"Blue\": ( 0, 0, 255 ), \"Pink\": ( 255, 192,", "( 255, 140, 0 ), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": (", "65, 105, 225 ), \"Sienna\": ( 160, 82, 45 ), \"Thistle\": ( 216,", "188, 143, 143 ), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": ( 216,", "), \"OrangeRed\": ( 255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170 ),", "182, 193 ), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\": ( 255, 215,", "\"LightYellow\": ( 255, 255, 224 ), \"PowderBlue\": ( 176, 224, 230 ), \"RoyalBlue\":", "165, 0 ), \"Red\": ( 255, 0, 0 ), \"Wheat\": ( 245, 222,", "( 240, 230, 140 ), \"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": (", "), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": ( 25, 25, 112 ),", "( 72, 61, 139 ), \"Green\": ( 0, 128, 0 ), \"Beige\": (", "), \"FloralWhite\": ( 255, 250, 240 ), \"LavenderBlush\": ( 255, 240, 245 ),", "), \"LightSalmon\": ( 255, 160, 122 ), \"PaleVioletRed\": ( 216, 112, 147 ),", "209, 204 ), \"Orange\": ( 255, 165, 0 ), \"Red\": ( 255, 0,", "255 ), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": ( 0, 139, 139", "71 ), \"WhiteSmoke\": ( 245, 245, 245 ), \"MediumSpringGreen\": ( 0, 250, 154", "\"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": ( 220, 20, 60 ), \"White\":", "0, 255, 255 ), \"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": ( 25,", "), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": ( 175, 238, 238 ),", "34, 34 ), \"Violet\": ( 238, 130, 238 ), \"Grey\": ( 128, 128,", "), \"DimGrey\": ( 105, 105, 105 ), \"Tan\": ( 210, 180, 140 ),", "255, 212 ), \"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": ( 47, 79,", "150, 122 ), \"RosyBrown\": ( 188, 143, 143 ), \"LightSalmon\": ( 255, 160,", "( 124, 252, 0 ), \"AliceBlue\": ( 240, 248, 255 ), \"Crimson\": (", "144 ), \"Gold\": ( 255, 215, 0 ), \"OldLace\": ( 253, 245, 230", "255, 255 ), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": ( 255, 250,", "), \"LightSteelBlue\": ( 176, 196, 222 ), \"DimGrey\": ( 105, 105, 105 ),", "119, 136, 153 ), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\": ( 221,", "( 245, 222, 179 ), \"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": (", "90, 205 ), \"YellowGreen\": ( 154, 205, 50 ), \"Aquamarine\": ( 127, 255,", "169, 169 ), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": ( 139, 0,", "\"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": ( 245, 255, 250 ), \"CornflowerBlue\":", "215, 0 ), \"OldLace\": ( 253, 245, 230 ) } lowercase_html_colors = dict(", "( 255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": (", "69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": ( 105, 105,", "255, 182, 193 ), \"SlateGrey\": ( 112, 128, 144 ), \"Gold\": ( 255,", "( 255, 248, 220 ), \"Bisque\": ( 255, 228, 196 ), \"PaleGreen\": (", "), \"Maroon\": ( 128, 0, 0 ), \"LightPink\": ( 255, 182, 193 ),", "245, 255, 250 ), \"CornflowerBlue\": ( 100, 149, 237 ), \"HotPink\": ( 255,", "\"MediumPurple\": ( 147, 112, 216 ), \"MidnightBlue\": ( 25, 25, 112 ), \"Coral\":", "216, 230 ), \"Ivory\": ( 255, 255, 240 ), \"MediumVioletRed\": ( 199, 21,", "255, 228, 196 ), \"PaleGreen\": ( 152, 251, 152 ), \"Brown\": ( 165,", "), \"PeachPuff\": ( 255, 218, 185 ), \"Plum\": ( 221, 160, 221 ),", "\"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\":", "), \"Beige\": ( 245, 245, 220 ), \"Teal\": ( 0, 128, 128 ),", "), \"Aquamarine\": ( 127, 255, 212 ), \"LightCoral\": ( 240, 128, 128 ),", "119, 136, 153 ), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": ( 147,", "( 128, 0, 0 ), \"LightPink\": ( 255, 182, 193 ), \"SlateGrey\": (", "( 169, 169, 169 ), \"SaddleBrown\": ( 139, 69, 19 ), \"DarkMagenta\": (", "228, 181 ), \"Turquoise\": ( 64, 224, 208 ), \"DarkSlateBlue\": ( 72, 61,", "82, 45 ), \"Thistle\": ( 216, 191, 216 ), \"Lime\": ( 0, 255,", "240, 245 ), \"SeaGreen\": ( 46, 139, 87 ), \"Lavender\": ( 230, 230,", "250, 250 ), \"SteelBlue\": ( 70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104,", "0 ), \"LightBlue\": ( 173, 216, 230 ), \"Ivory\": ( 255, 255, 240", "0, 255, 255 ), \"ForestGreen\": ( 34, 139, 34 ), \"LemonChiffon\": ( 255,", "in capitalized_html_colors.items()) ) #lowercase_html_colors = { key.lower(): value for key, value in capitalized_html_colors.items()", "), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\": ( 255, 0, 255 ),", "( 70, 130, 180 ), \"MediumSlateBlue\": ( 123, 104, 238 ), \"Black\": (", "238 ), \"Grey\": ( 128, 128, 128 ), \"LightGreen\": ( 144, 238, 144", "), \"DeepPink\": ( 255, 20, 147 ), \"SeaShell\": ( 255, 245, 238 ),", "128, 128 ), \"LightGreen\": ( 144, 238, 144 ), \"Linen\": ( 250, 240,", "50, 204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": ( 107, 142,", "( 221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": (", "( 169, 169, 169 ), \"DarkCyan\": ( 0, 139, 139 ), \"DarkSlateGrey\": (", "245, 230 ) } lowercase_html_colors = dict( ((key.lower(), value) for key, value in", "128, 0, 128 ), \"PapayaWhip\": ( 255, 239, 213 ), \"Olive\": ( 128,", "( 255, 160, 122 ), \"PaleVioletRed\": ( 216, 112, 147 ), \"FireBrick\": (", "205 ), \"DarkOliveGreen\": ( 85, 107, 47 ), \"DarkSeaGreen\": ( 143, 188, 143", "\"BurlyWood\": ( 222, 184, 135 ), \"MediumBlue\": ( 0, 0, 205 ), \"DarkSalmon\":", "251, 152 ), \"Brown\": ( 165, 42, 42 ), \"DarkTurquoise\": ( 0, 206,", "0 ), \"SlateGray\": ( 112, 128, 144 ), \"DarkRed\": ( 139, 0, 0", "0, 255 ), \"DarkGrey\": ( 169, 169, 169 ), \"DarkCyan\": ( 0, 139,", "), \"Cyan\": ( 0, 255, 255 ), \"MediumPurple\": ( 147, 112, 216 ),", "0, 191, 255 ), \"DarkKhaki\": ( 189, 183, 107 ), \"LightGrey\": ( 211,", "138, 43, 226 ), \"LightSlateGrey\": ( 119, 136, 153 ), \"Cyan\": ( 0,", "224, 230 ), \"RoyalBlue\": ( 65, 105, 225 ), \"Sienna\": ( 160, 82,", "216, 191, 216 ), \"Lime\": ( 0, 255, 0 ), \"SlateGray\": ( 112,", "238, 238 ), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": ( 60, 179,", "), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": ( 186, 85, 211 ),", "255 ), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\": ( 138, 43, 226", "0, 205 ), \"DarkSalmon\": ( 233, 150, 122 ), \"RosyBrown\": ( 188, 143,", "128, 128, 128 ), \"LightGreen\": ( 144, 238, 144 ), \"Linen\": ( 250,", "255, 69, 0 ), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": ( 105,", "), \"MistyRose\": ( 255, 228, 225 ), \"SandyBrown\": ( 244, 164, 96 ),", "221, 160, 221 ), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": ( 245,", "140, 0 ), \"Fuchsia\": ( 255, 0, 255 ), \"LawnGreen\": ( 124, 252,", "), \"CadetBlue\": ( 95, 158, 160 ), \"LightYellow\": ( 255, 255, 224 ),", "{ key.lower(): value for key, value in capitalized_html_colors.items() } def get_color_tuple_by_name(colorname): return lowercase_html_colors[colorname.lower()]", "0, 100, 0 ), \"DarkGoldenRod\": ( 184, 134, 11 ), \"MediumOrchid\": ( 186,", "130, 238 ), \"Grey\": ( 128, 128, 128 ), \"LightGreen\": ( 144, 238,", "\"FireBrick\": ( 178, 34, 34 ), \"Violet\": ( 238, 130, 238 ), \"Grey\":", "85, 211 ), \"Chocolate\": ( 210, 105, 30 ), \"Purple\": ( 128, 0,", "), \"Orange\": ( 255, 165, 0 ), \"Red\": ( 255, 0, 0 ),", "192, 192 ), \"LightGray\": ( 211, 211, 211 ), \"GoldenRod\": ( 218, 165,", "( 230, 230, 250 ), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": (", "204 ), \"LightGoldenRodYellow\": ( 250, 250, 210 ), \"OliveDrab\": ( 107, 142, 35", "\"DarkSlateBlue\": ( 72, 61, 139 ), \"Green\": ( 0, 128, 0 ), \"Beige\":", "218, 165, 32 ), \"Indigo\": ( 75, 0, 130 ), \"CadetBlue\": ( 95,", "( 186, 85, 211 ), \"Chocolate\": ( 210, 105, 30 ), \"Purple\": (", "), \"DarkViolet\": ( 148, 0, 211 ), \"DarkGray\": ( 169, 169, 169 ),", "25, 25, 112 ), \"Coral\": ( 255, 127, 80 ), \"PaleTurquoise\": ( 175,", "240, 128, 128 ), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\": ( 240,", "135, 206, 250 ), \"SlateBlue\": ( 106, 90, 205 ), \"YellowGreen\": ( 154,", "\"LightCoral\": ( 240, 128, 128 ), \"DarkSlateGray\": ( 47, 79, 79 ), \"Khaki\":", "), \"MediumAquaMarine\": ( 102, 205, 170 ), \"MintCream\": ( 245, 255, 250 ),", "218, 112, 214 ), \"Salmon\": ( 250, 128, 114 ), \"IndianRed\": ( 205,", "0, 255, 127 ), \"Navy\": ( 0, 0, 128 ), \"Orchid\": ( 218,", "), \"PaleGoldenRod\": ( 238, 232, 170 ), \"DimGray\": ( 105, 105, 105 ),", "250 ), \"BlanchedAlmond\": ( 255, 235, 205 ), \"DarkOliveGreen\": ( 85, 107, 47", "107 ), \"LightGrey\": ( 211, 211, 211 ), \"Yellow\": ( 255, 255, 0", "147 ), \"SeaShell\": ( 255, 245, 238 ), \"Magenta\": ( 255, 0, 255", "35 ), \"Chartreuse\": ( 127, 255, 0 ), \"Peru\": ( 205, 133, 63", "), \"LawnGreen\": ( 124, 252, 0 ), \"AliceBlue\": ( 240, 248, 255 ),", "\"LightCyan\": ( 224, 255, 255 ), \"LightSeaGreen\": ( 32, 178, 170 ), \"BlueViolet\":", "245, 245, 220 ), \"Teal\": ( 0, 128, 128 ), \"Azure\": ( 240,", "), \"HoneyDew\": ( 240, 255, 240 ), \"FloralWhite\": ( 255, 250, 240 ),", "\"Navy\": ( 0, 0, 128 ), \"Orchid\": ( 218, 112, 214 ), \"Salmon\":", "\"White\": ( 255, 255, 255 ), \"NavajoWhite\": ( 255, 222, 173 ), \"Cornsilk\":", "\"GreenYellow\": ( 173, 255, 47 ), \"DarkOrchid\": ( 153, 50, 204 ), \"LightGoldenRodYellow\":", "), \"Purple\": ( 128, 0, 128 ), \"PapayaWhip\": ( 255, 239, 213 ),", "( 175, 238, 238 ), \"Gray\": ( 128, 128, 128 ), \"MediumSeaGreen\": (" ]